#include <memory>
struct foo
{
std::unique_ptr<int> p;
};
int main()
{
foo bar { std::unique_ptr<int>(new int(42)) };
// okay
new foo { std::unique_ptr<int>(new int(42)) };
// error: no matching function for call to
// 'foo::foo(<brace-enclosed initializer list>)'
}
统一初始化是否不适用于动态对象,或者这是 g++ 4.6.1 的缺点?
它适用于 g++ 4.7.1,但如果 foo
继承自另一个类,main
中的两行 将无法编译:
struct baz
{
// no data members, just some member functions
};
struct foo : baz
{
std::unique_ptr<int> p;
};
再一次,我的编译器的缺点?还是统一初始化不能很好地处理继承?
最佳答案
它在 g++-4.7 下构建良好。所以大概是后者。我会看看是否可以通过文档找到更有力的证据。
并响应继承附录:
这个更简单的案例也无法编译:
struct baz
{
};
struct foo : baz
{
int b;
};
int main()
{
foo bar { 12 };
}
与:
testoo.cpp:14:18: error: no matching function for call to ‘foo::foo(<brace-enclosed initializer list>)’
testoo.cpp:14:18: note: candidates are:
testoo.cpp:7:8: note: foo::foo()
testoo.cpp:7:8: note: candidate expects 0 arguments, 1 provided
testoo.cpp:7:8: note: constexpr foo::foo(const foo&)
testoo.cpp:7:8: note: no known conversion for argument 1 from ‘int’ to ‘const foo&’
testoo.cpp:7:8: note: constexpr foo::foo(foo&&)
testoo.cpp:7:8: note: no known conversion for argument 1 from ‘int’ to ‘foo&&’
根据我对标准的阅读,您在第一个示例中得到了聚合初始化
:
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).
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.
请注意,这明确禁止了基类。综上所述——在存在基类的情况下不允许进行聚合初始化。因此,第二个示例都不会编译。
关于c++ - 动态对象的统一初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11394924/