Ad
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?
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
Related Questions
- → Comparing two large files are taking over four hours
- → Setting JSON node name to variable value
- → Compiling GLUT using Emscripten
- → Evaluate check box from a scanned image in node.js
- → Find an easy web server framework for mobile game
- → my https C++ code doesn't work on some sites (binance)
- → Error while opening pivx wallet on ubuntu
- → Why sending a POST by AJAX is interpreted by the HTTP Server as OPTIONS and sending by CURL is effectively a PUT?
- → Python reading in one line multiple types for a calculator
- → How do I properly pass an argument to a function
- → Accessing Websql database with Qt
- → Using Mysql C API for c++ codes
- → How do I set constants at run-time in a c++ header file, imported through Cython?
Ad