c++ - 唯一指针类内初始化

标签 c++ c++11 unique-ptr in-class-initialization

假设我有一个要在类中初始化的unique_ptr 成员对象,请参见下面的代码。为什么我必须使用统一初始化(花括号)?第二个声明吐出一个错误,类似于

so.cpp:10:31: error: expected parameter declarator
std::unique_ptr<Foo> upf2(new Foo);
                          ^
so.cpp:10:31: error: expected ')'
so.cpp:10:30: note: to match this '('
std::unique_ptr<Foo> upf2(new Foo);                             ^
2 errors generated. 

而且我不认为这是最令人烦恼的解析问题,至少我不这么认为。

#include <memory>

class Foo
{

};

class Bar{
    std::unique_ptr<Foo> upf1{new Foo}; // works fine
//    std::unique_ptr<Foo> upf2(new Foo); // error here
};

int main() 
{
    Bar bar;
}

最佳答案

因为这是规则。类内初始化器必须使用“大括号”或“等于”;事实上,语法元素称为 brace-or-equal-initializer

int equals = 42;                      // OK
std::unique_ptr<Foo> braces{new Foo}; // Also OK

我不知道为什么不允许使用括号;也许是为了避免初始化看起来像函数声明的可能性。当直接初始化和大括号初始化之间存在差异时,这可能会很烦人:

std::vector<int> bad(6);                     // ERROR: parentheses not allowed
std::vector<int> good{6};                    // OK but not the same
std::vector<int> ugly = std::vector<int>(6); // OK but ugly

关于c++ - 唯一指针类内初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26269382/

相关文章:

c++ - 由于 Compressed_pa​​ir,无法编译纯虚拟结构和 unique_ptr 的 DLL 导入

c++ - 无法同时在两个 10Gbps 接口(interface)上达到全线速

c++ - 是否可以强制 CMake 在其他项目类型生成时生成 Visual Studio 项目?

c++ - 运算符重载模板参数

c++ - 将派生类的 unique_ptr 添加到基类 unique_ptr 的 vector 中

c++ - 如何转发声明自定义unique_ptr

c++ - 专家的字符串和字符映射问题

c++ - For 循环不停止

c++ - C++ 中的 std::thread 库是否支持嵌套线程?

c++ - 错误 : 'int_type' does not name a type - How to inherit typedefs and usings