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

后端 未结 3 1784
爱一瞬间的悲伤
爱一瞬间的悲伤 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:02

    The standard says (§ 20.8.1.2.1 ¶ 16, emphasis added) that the move constructor of std::unique_ptr

    unique_ptr(unique_ptr&& u) noexcept;
    

    Constructs a unique_ptr by transferring ownership from u to *this.

    Therefore, after you move-construct the temporary object that gets passed as argument to attachActor form your tony, tony no longer owns the object and hence tony.get() == nullptr. (This is one of the few cases where the standard library actually makes assertions about the state of a moved-away-from object.)

    However, the desire to return the reference can be fulfilled without resorting to naked new and raw pointers.

    Tony&
    Movie::addTony()
    {
      auto tony = std::make_unique();
      auto p = tony.get();
      attachActor(std::move(tony));
      return *p;
    }
    

    This code assumes that attachActor will not drop its argument on the floor. Otherwise, the pointer p would dangle after attachActor has returned. If this cannot be relied upon, you'll have to re-design your interface and use shared pointers instead.

    std::shared_ptr
    Movie::addTony()
    {
      auto tony = std::make_shared();
      attachActor(tony);
      return tony;
    }
    

提交回复
热议问题