Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is unique_ptr<T> not constructible from T*?

Tags:

c++

unique-ptr

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?

like image 642
Mikhail T. Avatar asked Jan 25 '23 11:01

Mikhail T.


1 Answers

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);
like image 111
NathanOliver Avatar answered Feb 04 '23 17:02

NathanOliver