使用构造函数与支撑初始化列表进行初始化类和结构的规则是什么?

时间:2018-12-31 03:21:45

标签: c++ c++11 constructor initializer-list list-initialization

我已经在线搜索了该问题的答案,但尚未找到满意的答案。我想知道用于结构和类类型的对象的初始化的所有规则是什么,特别是涉及构造函数和支撑初始化列表时。结构和类的规则也不同吗?

让我们假设我们有一个名为Rectangle的类或结构。

#include <iostream>
using namespace std;

class Rectangle {
  public:
    Rectangle() : x(5.0), y(6.0), width(7.0), height(8.0) {}

    void printMe()
    {
        cout << "The rectangle is located at (" << x << ',' << y << ") and is " << width << " x " << height << endl;
    }
    double x;
    double y;
    double width;
    double height;
};


int main()
{
    Rectangle r = {0.0, 0.0, 3.0, 4.0};
    r.printMe();

    Rectangle s;  // uninitialized!
    s.printMe();
}

我尝试使用普通的旧的带括号的初始值设定项列表来初始化Rectangle r,方法与在C语言中通常执行的方式相同。但是,g++给出以下错误:

constructor_vs_initializer_list.cpp: In function ‘int main()’:
constructor_vs_initializer_list.cpp:21:38: error: could not convert ‘{0.0, 0.0, 3.0e+0, 4.0e+0}’ from ‘<brace-enclosed initializer list>’ to ‘Rectangle’
     Rectangle r = {0.0, 0.0, 3.0, 4.0};
                                      ^

嗯...。乍一看,这不是非常有用的错误消息。但是,我认为它与构造函数有关,因为如果删除它,代码将编译并运行!我认为这将是一个悖论,大括号的初始化程序列表和构造函数都在竞争似乎初始化的数据成员。

但是,当我使数据成员成为private时,在删除了构造函数之后,再次显示了相同的错误消息!

我想知道初始化数据成员的优先规则是什么。大括号的初始化程序列表与您自己定义的构造函数相比如何?它与C ++ 11功能(= default构造函数和类内成员初始化程序)相比如何?我认为初始化对象数据成员的这些不同方式会相互冲突。

Rectangle() = default;
...
double x = 1.0;

我并不是在写将它们混合在一起不一定是 good 代码,只是我认为代码应该很好理解。谢谢。

3 个答案:

答案 0 :(得分:2)

CPP标准草案n4713声明了有关聚合初始化的信息:

  

11.6.1聚合[dcl.init.aggr]
  1集合是具有
的数组或类   (1.1)-没有用户提供的,显式的或继承的构造函数,
  (1.2)—没有私有或受保护的非静态数据成员

在您的情况下,您在第一种情况下有一个用户提供的构造函数,在第二种情况下有一个私有数据成员,分别违反了上述(1.1)和(1.2)的要点。

答案 1 :(得分:2)

这是一个说明差异的示例。 C ++中的初始化非常复杂。参见:https://blog.tartanllama.xyz/initialization-is-bonkers/

通常最好使用default member initializersinitialization lists。您在构造函数中做的正确的事情。只需使用direct-list-initializationdirect initialization调用构造函数,以免使人们感到困惑。 通常,您将只使用copy-list-initialization来初始化聚合,而无需用户提供构造函数。

#include <iostream>

struct A {
    int i;
};

struct B {
    B() = default;
    int i;
};

struct C {
    C();
    int i;
};

C::C() = default;

struct D {
    D(){};
    int i;
};

struct E : public D {
};

struct F {
    F(int i = 5) {}
    int i;
};

struct G {
    G() = delete;
    int i;
};

int main() {
    // g++ (v 8.2.1) provides good warnings about uninitialized values.
    // clang++ (v 7.0.1) does not.
    // Technically, they are initialized to 'indeterminate values', but it is
    // easier to refer to the member variables as uninitialized.

    {
        // All of the following are 'default initialized', meaning they are not even
        // zero-initialized. Members are UNINITIALIZED (Technically, they are
        // initialized to 'indeterminate' values.
        // Either nothing is done, or the default constructor is called (in
        // which nothing is done).
        A a;
        B b;
        C c;
        D d;
        E e;
        F f;

        std::cout << "a: " << a.i << std::endl;
        std::cout << "b: " << b.i << std::endl;
        std::cout << "c: " << c.i << std::endl;
        std::cout << "d: " << d.i << std::endl;
        std::cout << "e: " << e.i << std::endl;
        std::cout << "f: " << f.i << std::endl;
        std::cout << std::endl;
    } {
        // This is more complex, as these are all 'list initialized'.
        // Thank you, infinite wisdom of the C++ committee.

        A a{};
        // Direct list initialization -> aggregate initialization
        //  - A has no user-provided constructor and
        // thus is an aggregate, and agg. init. takes place.
        // This 'value initializes' all *MEMBERS* (unless a default member
        // initializer exists, which it does not here).
        // Value initialization of non-class types results in
        // zero-initialization. (member `i` is zero-initialized)

        A a2 = {};
        // same thing, but via copy list initialization

        A a3{{}};
        // recursive, initializes `i` with {}, which zero initializes `i`.

        A a4{0};
        // recursive, initializes `i` 0;
        // Could also do `A a4 = {0}`

        A a5{a};
        // direct intialization of `a5` with `a`.
        // Implicit copy constructor chosen by overload resolution.

        A a6{A{}};
        // post C++17, direct initializes a6 with a prvalue of type A, that is
        // aggregate initialized as above. NOT copy/move initialized, but
        // instead initialized via the "initializer expression itself".
        // I assume this means the value of a6 is directly set via as if it were
        // being aggregate initialized.

        B b{};
        // Same as A. `B() = default;` does NOT specify a user-provided
        // constructor

        C c{};
        // Because the first declaration of `C()` is not `C() = default;`,
        // this DOES have a user-provided constructor, and 'value initializaton'
        // is performed.
        // NOTE: this value intializes `C`, not the *MEMBERS* of `C`.
        // Because `C` is a normal class type, value initialization just calls
        // the default constructor, which does nothing, and leaves all members
        // uninitialized.

        D d{};
        // D is a class type that is list/direct initialization -> value
        // inititalizaton -> default initialization -> call constructor ->
        // members are left unitialized.

        E e{};
        // List initialization -> value initialization -> default initialization
        // -> calls implicitly defined default constructor -> Calls default
        // constructor of bases -> leaves E::D.i uninitialized

        F f{};
        // List/direct initialization -> value initialization -> calls default
        // constructor with default arguments -> leaves F.i uninitialized

        // G g{}; 
        // Fails to compile.
        // list initialization -> value initialization -> default initialization
        // -> deleted default constructor selected by overload resolution ->
        // fails to compile

        std::cout << "a: " << a.i << std::endl;
        std::cout << "a2: " << a2.i << std::endl;
        std::cout << "a3: " << a3.i << std::endl;
        std::cout << "a4: " << a4.i << std::endl;
        std::cout << "a5: " << a5.i << std::endl;
        std::cout << "a6: " << a6.i << std::endl;
        std::cout << "b: " << b.i << std::endl;
        std::cout << "c: " << c.i << std::endl;
        std::cout << "d: " << d.i << std::endl;
        std::cout << "e: " << e.i << std::endl;
        std::cout << "f: " << f.i << std::endl;
    }
}

答案 2 :(得分:-1)

我不确定“支撑初始化列表”是什么意思,但是您不能使用花括号来初始化这样的对象。您可以使用花括号来初始化聚合结构(所有数据成员都是公共的,并且没有构造函数),但这实际上不是最佳实践。

最佳做法是将数据成员设为私有,并使用如下构造函数:

#include <iostream>
using namespace std;

class Rectangle {
private:
    double _x = 0.0;
    double _y = 0.0;
    double _w = 0.0;
    double _h = 0.0;
public:
    Rectangle( const double & x, const double & y, const double & w, const double & h ) : _x(x), _y(y), _w(w), _h(h) {}
    Rectangle(){}

    void printMe() const
    {
        cout << "The rectangle is located at (" << _x << ',' << _y << ") and is " << _w << " x " << _h << endl;
    }
};


int main()
{
    Rectangle r(0.0, 0.0, 3.0, 4.0);
    r.printMe();

    Rectangle s;  // default value - all zeros
    s.printMe();
}

现在,对象数据已正确封装,防止了不必要的副作用,您可以使用构造函数轻松地初始化对象。唯一的区别是您将使用括号而不是括号。

还要注意,我已经为数据成员提供了默认值,并且提供了默认构造函数。这也是最佳做法,可以防止未初始化的数据出现问题。

请记住,构造函数只是具有语法功能的函数,以支持其作为构造函数的角色。函数的所有基本规则均适用。 (还要注意,我已经对函数参数进行了const引用,以避免两次复制值。)

相关问题