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.