Ajay Brahmakshatriya
Ajay Brahmakshatriya

Reputation: 9203

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?

Upvotes: 0

Views: 112

Answers (2)

David G
David G

Reputation: 96790

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.

Upvotes: 2

lorro
lorro

Reputation: 10880

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()

Upvotes: 2

Related Questions