So when using shared_ptr
you can write:
shared_ptr var(new Type());
I wonder why they didn\'t allow a
The syntax:
shared_ptr 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
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();