简体   繁体   中英

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.

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.

When you do this

Foo foo;
X x(&foo);

foo is allocated in the stack. Objects in stack cannot be included in unique_ptr. You only can do it if the object is in the heap:

Foo* foo = new Foo( );
X x( foo );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM