So when using shared_ptr
you can write:
shared_ptr var(new Type());
I wonder why they didn\'t allow a
Why [doesn't]
shared_ptr
permit direct assignment [copy initialization]?
Because it is explicit
, see here and here.
I wonder what the rationale [is] behind it? (From a comment now removed)
TL;DR, making any constructor (or cast) explicit
is to prevent it from participating in implicit conversion sequences.
The requirement for the explicit
is better illustrated with the shared_ptr<>
is an argument for a function.
void func(std::shared_ptr arg)
{
//...
}
And called as;
Type a;
func(&a);
This would compile, and as written and is undesired and wrong; it won't behave as expected.
It gets further complicated with adding user defined (implicit) conversions (casting operators) into the mix.
struct Type {
};
struct Type2 {
operator Type*() const { return nullptr; }
};
Then the following function (if not explicit) would compile, but offers a horrible bug...
Type2 a;
func(a);