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

Difference between foo = bar and foo{ bar }

I was under the impression that foo = bar and foo{ bar } both did the same thing and it was just a matter of preference, but in my code foo = bar gives an error but foo{ bar } does not:

std::vector<std::unique_ptr<bar>> bars;

bar& myFunction() {

    bar* b = new bar();
    std::unique_ptr<bar> foo{ b }; //works fine
    std::unique_ptr<bar> foo = b; //error
    bars.emplace_back(std::move(foo));

    return *b;

}

Any idea why this is happening?

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 :

The second one does not work because unique_ptr has an explicit constructor:

explicit unique_ptr( pointer p ) noexcept;

The below line:

std::unique_ptr<bar> foo = b;

tries to call the above-mentioned constructor of std::unique_ptr. And because of the explicit keyword, that call to the constructor is invalid.

So only these two will work:

std::unique_ptr<bar> foo { b };
std::unique_ptr<bar> foo ( b ); // or this
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