简体   繁体   中英

c++14 unique_ptr and make unique_ptr error use of deleted 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 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?

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.

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