Reputation: 87
I have a function like this..
unique_ptr<Node> test(unique_ptr<Node> &&node, string key)
{
if(!node)
{
return make_unique<Node>(key);
}
else
return node;
}
I want to create a node if the node is null, or to return the node. but it errors out saying "use of deleted function 'std::unique_ptr' ". What have I done wrong?
Upvotes: 4
Views: 1734
Reputation: 48655
The problem is the way you are calling the function. But first of all you should accept your std::unique_ptr
by value, not r-reference.
Then you need to std::move()
your pointer when calling the function:
// accept by value
std::unique_ptr<Node> test(std::unique_ptr<Node> node)
{
if(!node)
return std::make_unique<Node>();
return node;
}
int main()
{
auto n = std::make_unique<Node>();
n = test(std::move(n)); // move the pointer
}
A std::unique_ptr
can't be copied otherwise it would not be unique. You hav to move them.
Upvotes: 4