唯一指针类的初始化 [英] Unique pointer in-class initialization

查看:366
本文介绍了唯一指针类的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 unique_ptr 成员对象,我想在类中初始化,请参阅下面的代码。为什么我必须使用统一的初始化(花括号)?第二个声明发生错误,例如

  so.cpp:10:3​​1:error:expected parameter declarator 
std :: unique_ptr< Foo> upf2(new Foo);
^
so.cpp:10:3​​1:error:expected')'
so.cpp:10:3​​0:注意:匹配这个'('
std :: unique_ptr< Foo> upf2(new Foo); ^
产生两个错误。

不认为是一个最烦躁的解析问题,至少我不这么认为。

  #include< memory> 

class Foo
{

};

class Bar {
std :: unique_ptr< Foo> upf1 {new Foo}; //工作正常
// std :: unique_ptr< Foo> upf2(new Foo); //错误在这里
};

int main()
{
Bar bar;
}


解决方案>

非静态数据成员初始值设定器(NSDMI)必须使用大括号或初始值设定项 (expression-list)不允许初始化形式。



由于 N2756 解释,为了让NSDMI更像传统的构造函数成员初始化器列表,初始化器中的名称在整个类的范围内查找。不幸的是,这意味着允许圆括号初始化器将无法确定在解析声明时是否是初始化器或函数声明:

  //不是真正的代码
struct X {
int i(x); // initializer
static int x;
};

struct Y {
int i(x); // function
typedef int x;
};

本文讨论了一些可能的方法来解决这个问题,一个声明是一个声明或它不是一个类型,除非你说它是一个类型),但两者都不是很吸引人,并且潜在的混乱被认为超过允许这种形式的初始化的好处。


Suppose I have a unique_ptr member object that I want to initialize in-class, see the code below. Why do I have to use uniform initialization (curly braces)? The second declaration spits an error, something like

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. 

And I don't think is a most vexing parse issue, at least I don't believe so.

#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;
}

解决方案

A non-static data member initializer (NSDMI) must use a brace-or-equal-initializer. The ( expression-list ) form of initialization isn't allowed.

As N2756 explains, in order to allow NSDMIs to behave more like traditional constructor member initializer lists, the names inside initializers are looked up in the scope of the entire class. Unfortunately, this means that allowing parentheses initializers would make it impossible to determine whether something is an initializer or a function declaration at the time the declaration is parsed:

// not real code
struct X {
    int i(x);    // initializer
    static int x;
};

struct Y {
    int i(x);    // function
    typedef int x;
};

The paper discussed a couple possible ways to fix this short of banning it altogether ("everything that can be a declaration is a declaration" or "it's not a type unless you say it's a type"), but neither is very appealing, and the potential confusion was deemed to outweigh the benefit of allowing this form of initialization.

这篇关于唯一指针类的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆