Ad

Difference Between Foo = Bar And Foo{ Bar }

- 1 answer

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?

Ad

Answer

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
Ad
source: stackoverflow.com
Ad