I'm relatively new to cpp, and am learning about smart points. I'm wondering the following:
Why is constructing an std::unique_ptr
with an lvalue
allowed?
Wouldn't it be safer to only allow the construction of an std::unique_ptr
with rvalues to avoid evil things?
std::unique_ptr<int> createInt() {
int* a = new int(99);
std::unique_ptr<int> foo(a);
delete a;
return foo;
}
I realize you'd have to be crazy to write something like that but I'd be nice to have the compiler yell at you for it. So I'm left wondering, why is lvalue initialization of unique_ptr a thing?
EDIT: User @aler egal put my thoughts more elagantly:
"In principle, you could have a constructor
unique_ptr<int>(int*&& ptr)
which assumes ownership of ptr and then sets it tonull
. That would prevent a use-after-free in this specific example (because you'd be forced tostd::move(a)
and because calling delete on a null pointer has no effect) but it would be a very strange anti-pattern."