Search code examples
c++c++11unique-ptrobject-lifetime

Error associated with std::unique_ptr


I'm having a problem with std::unique_ptr. I thought I understood them but clearly not.

I have the following code:

X::X() : m_foo(nullptr),
{
    m_foo = std::unique_ptr<Foo>(new Foo());
}

X::X(Foo* foo) : m_foo(nullptr),
{
    m_foo = std::unique_ptr<Foo>(foo);
}

std::unique_ptr<Foo> m_foo;

When I construct X as follows:

Foo foo;
X x(&foo);

I get an error at runtime telling me that 'error for object 0x101f7eec0: pointer being freed was not allocated'.

However, when I construct X as follows:

Foo foo;
X x;

no such error occurs.

If I add the following destructor:

X::~X()
{
    m_foo.release();
}

everything works OK.

I'm not really sure why the error occurs in the first place nor why releasing foo clears it.

Please can someone explain.


Solution

  • std::unique_ptr is for managing lifetime of dynamically allocated objects (that is, objects created using new and the likes).

    In your failing example, foo is created with automatic storage, so there is no need to manage its lifetime (and attempting to do so anyway will result in the error you observed). The compiler will automatically destroy it once it goes out of scope.