Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a unique_ptr from a pointer

Tags:

c++

unique-ptr

The following code gives an error:

void EntityContainer::AddChild(Entity* child) 
{ 
    unique_ptr<Entity> childPtr(child);
    children.push_back(childPtr);
}

I take it this may not be the correct way of creating a unique_ptr to an existing object. How could this be done properly? The above code gives the following error:

1>c:\program files (x86)\microsoft visual studio 11.0\vc\include\xmemory0(617): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'
like image 258
JordanBell Avatar asked Dec 20 '22 14:12

JordanBell


1 Answers

You cannot copy unique pointers. Because they are... unique. However, you can move them:

children.push_back(std::move(childPtr));

That's a bit redundant, so you could instead say:

children.push_back(std::unique_ptr<Entity>(child));

However, direct construction of container elements is already provided by the emplace construction:

children.emplace_back(child);

None of this quite hits the mark, though. The problem is really that you have a function that silently takes ownership of something, and that is completely invisible in the interface. So really you should change the function signature and make the caller give you ownership explicitly:

void EntityContainer::AddChild(std::unique_ptr<Entity> child) 
{ 
    children.push_back(std::move(child));
}

Now it is no longer your fault if the user gets the ownership semantics wrong!

like image 57
Kerrek SB Avatar answered Jan 02 '23 20:01

Kerrek SB