What happens to unique_ptr after std::move()?

后端 未结 3 1773
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 19:43

This code is what I want to do:

Tony& Movie::addTony()
{
    Tony *newTony = new Tony;
    std::unique_ptr tony(newTony);
    attachActor(std::m         


        
3条回答
  •  北海茫月
    2021-02-03 20:07

    No, you cannot do that instead. Moving the unique_ptr nulls it. If it didn't, then it would not be unique. I am of course assuming that attachActor doesn't do something silly like this:

    attachActor(std::unique_ptr&&) {
        // take the unique_ptr by r-value reference,
        // and then don't move from it, leaving the
        // original intact
    }
    

    Section 20.8.1 paragraph 4.

    Additionally, u (the unique_ptr object) can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold:
       -- u2.p is equal to the pre-transfer u.p,
       -- u.p is equal to nullptr, and
       -- if the pre-transfer u.d maintained state, such state has been transferred to u2.d.

提交回复
热议问题