c++ - 动态对象的统一初始化

标签 c++ c++11 initialization unique-ptr uniform-initialization

#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/

相关文章:

c++ - std::find 在 std::vector<std::reference_wrapper<T>> 上失败并出现 "no match for ‘operator==’“当 T 在 namespace 中时出现错误

c++11 - 为什么委托(delegate)给默认构造函数不为零初始化成员变量

c++ - std::atomic::load 如何实现

Android AES 和初始化向量

.net - 这是在 vb.net 中用 null 初始化字符串的最佳方法

c++ - 使用正在进行的函数调用销毁对象

c++ - 有没有一种方法可以强制gradle一次只为一个项目编译c++代码(并且只有它)?

c++ - 为什么unique_ptr不允许const_cast?

c - 结构中的数组在初始化后充满了垃圾

c++ - 在递归下降解析器中使用第一集