Mikhail T.
Mikhail T.

Reputation: 4027

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

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?

Upvotes: 4

Views: 231

Answers (1)

NathanOliver
NathanOliver

Reputation: 180998

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);

Upvotes: 8

Related Questions