Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading