Initialize array in constructor without using default constructor or assignment

后端 未结 4 468
日久生厌
日久生厌 2021-01-13 03:56

Consider:

struct A {

 A (int);

 A (const A &);
};

struct B {

 A foo [2];

 B (const A & x, const A & y)
 : foo {x, y} /* HERE IS THE PROBLEM          


        
4条回答
  •  忘掉有多难
    2021-01-13 04:30

    Your question is similar to this previous question: C++: constructor initializer for arrays

    Your main suggestion (make two members foo_a and foo_b) is probably the best way of doing things, provided that you'll need only two elements. There's no way of initializing array elements with anything but the type's default constructor in an initializer list, as you're trying to do in your example. Edit: Sorry, I didn't see that you were using C++0x. In C++0x you should be able to initialize as you wanted to do, provided that A is copyable or movable. I don't know about GCC 4.3's support for this, though.

    Be careful using char arrays and placement new - char arrays aren't necessarily aligned properly to construct an A, and doing this can result in undefined behavior.

    Some other suggestions:

提交回复
热议问题