简体   繁体   中英

Copy constructor difference for std::unique_ptr

If my understanding is correct, the following declarations should both call the copy constructor of T which takes type of x as a parameter.

T t = x;
T t(x);

But when I do the same for std::unique_ptr<int> I get an error with the first declaration, while the second compiles and does what is expected.

std::unique_ptr<int> x = new int();
std::unique_ptr<int> x (new int());

Is there a difference in the two syntax for calling the copy constructor?

Constructor of std::unique_ptr<> is explicit , which means, you need to write it in the first case:

std::unique_ptr<int> x = std::unique_ptr<int>(new int());
// or
auto x = std::unique_ptr<int>(new int());
// or make_unique()

std::unique_ptr::unique_ptr( pointer p ) is an explicit constructor, so that form of initialization is not allowed. Initializing with = always requires a converting-constructor for implicit conversions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM