简体   繁体   中英

Moving an object from one unique_ptr to another C++

I've created 2 classes: Crane and Container . Crane has a private member unique_ptr<Container> container and a public method load() taking a unique_ptr<Container> as a parameter, like this:

void Crane::load(unique_ptr<Container> container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}

My goal here is to give a crane a container to hold, so other Crane methods can put the currently held container down in a warehouse, check its id, weight, etc.

Now, in main() I create 2 objects: Crane crane; and unique_ptr<Container> con(new Container(1)); .

In main() , when I want to call crane.load(con) , I get this error:

error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Container; _Dp = std::default_delete<Container>]'

I thought that this is the way when you want to change ownership of an object? Please help.

std::unique_ptr cannot be copied (its copy constructor is deleted). Allowing copies would break the uniqueness of its pointer ownership.

The container parameter of load() is taken by value, so when your code passes the con variable to load() , the compiler tries to copy-construct container , thus the error (which, if you read it carefully, is complaining about the deleted copy constructor).

You need to use crane.load(std::move(con)); instead, so the compiler can move-construct container so ownership of the pointer is moved from con to container .

The alternative is to change load() to take container by reference instead:

void Crane::load(unique_ptr<Container> &container)
{
    if(isUnloaded())
    {
        this->container = move(container);
    }
}

That way, crane.load(con); will work, and take ownership only if isUnloaded() is false, otherwise ownership stays with the caller (for instance, if you wanted to then try loading the container to a different Crane ).

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