Reputation: 5364
In the following code
struct BinaryNode {
int val;
BinaryNode *leftchild, *rightchild;
};
struct NaryNode {
int val;
std::vector<NaryNode*> children;
};
I can initialize the first struct as
std::unique_ptr<BinaryNode> bnode1(new BinaryNode{4});
but the second one fails
std::unique_ptr<NaryNode> nnode1(new NaryNode{4});
What gives ?
EDIT: The compiler error is
tree.cpp: In function ‘int main()’:
tree.cpp:41:68: error: no matching function for call to ‘NaryNode::NaryNode(<brace-enclosed initializer list>)’
tree.cpp:41:68: note: candidates are:
tree.cpp:10:8: note: NaryNode::NaryNode()
tree.cpp:10:8: note: candidate expects 0 arguments, 2 provided
tree.cpp:10:8: note: NaryNode::NaryNode(const NaryNode&)
tree.cpp:10:8: note: candidate expects 1 argument, 2 provided
tree.cpp:10:8: note: NaryNode::NaryNode(NaryNode&&)
tree.cpp:10:8: note: candidate expects 1 argument, 2 provided
Version:
$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Build command:
$ g++ -std=c++0x tree.cpp
Upvotes: 2
Views: 1510
Reputation: 121971
From section 8.5.1 Aggregates of the c++11 standard (draft n3337):
1 An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
2 When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order...
And from section 8.5.4 List-initialization:
List-initialization can be used
- as the initializer in a variable definition (8.5)
- as the initializer in a new expression (5.3.4)
This means NaryNode
is an aggregate and can be list initialized (using {}
).
The compiler is incorrect to reject the NaryNode
snippet, g++ v4.7.2 compiles it fine (see http://ideone.com/LewfQE).
Upvotes: 1