C ++ 14 unique_ptr and make unique_ptr error using remote function 'std :: unique-ptr'
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 node is null or returns node. but he is wrong saying "using remote function" std :: unique_ptr "What did I do wrong?
+3
source to share
1 answer
The problem is how you call the function. But first of all, you must accept yours std::unique_ptr
by value, not by r-link.
Then you need to std::move()
provide a 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
cannot be copied, otherwise it will not be unique. You can move them.
+3
source to share