Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - Unique pointer in-class initialization

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because those are the rules. In-class initialisers must use "braces" or "equals"; in fact, the syntactical element is called a brace-or-equal-initializer.

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

I don't know why parentheses aren't allowed; perhaps to avoid the possibility of the initialisation looking like a function declaration. It can be annoying when there's a difference between direct and brace initialisation:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...