So when using shared_ptr<Type>
you can write:
shared_ptr<Type> var(new Type());
I wonder why they didn't allow a much simpler and better (imo):
shared_ptr<Type> var = new Type();
Instead to achieve such functionality you need to use .reset()
:
shared_ptr<Type> var;
var.reset(new Type());
I am used to OpenCV Ptr class that is a smart pointer that allows direct assignment and everything works fine
The syntax:
shared_ptr<Type> var = new Type();
Is copy initialization. This is the type of initialization used for function arguments.
If it were allowed, you could accidentally pass a plain pointer to a function taking a smart pointer. Moreover, if during maintenance, someone changed void foo(P*)
to void foo(std::shared_ptr<P>)
that would compile just as fine, resulting in undefined behaviour.
Since this operation is essentially taking an ownership of a plain pointer this operation has to be done explicitly. This is why the shared_ptr
constructor that takes a plain pointer is made explicit
- to avoid accidental implicit conversions.
The safer and more efficient alternative is:
auto var = std::make_shared<Type>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With