What's "wrong" with this code, for a simple-minded example?
unique_ptr<char> meow = strdup("meow");
Whether or not I provide the "deleter" argument to the unique_ptr
template, a unique_ptr<T>
cannot be assigned from T*
.
Why wouldn't <memory>
offer this seemingly intuitive shortcut? Is it simply an oversight, or would such assignability be a fundamentally bad idea for some reason?
Why wouldn't
<memory>
offer this seemingly intuitive shortcut?
Imagine you have
int bar;
{
int * foo = &bar;
std::unique_ptr<int> uptr = foo;
// use uptr
}
When uptr
goes out of scope, it's going to try and do delete pointer;
, which will try to call delete
on memory that was not allocated by new
. That's undefined behavior and can cause all sorts of problems. Instead of allowing buggy code like that to be able to be written, the standard disallows it.
If you are really sure you want to construct a unique_ptr
from an existing pointer, and you know the default deleter is what you want, then you can use the form of
auto pointer_name = std::unique_ptr<type>(pointer_i_know_needs_to_be_deleted);
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