简体   繁体   中英

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?

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

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