Is the contents of a pointer to a unique_ptr's contents valid after the unique_ptr is moved?

后端 未结 1 1206
礼貌的吻别
礼貌的吻别 2021-01-19 02:48

I\'ve been led to understand that calling a member function on the contents of a moved-from std::unique_ptr is undefined behaviour. My question is: if I call

相关标签:
1条回答
  • 2021-01-19 02:59

    Merely moving the unique_ptr only changes the ownership on the pointed-to object, but does not invalidate (delete) it. The pointer pointed to by unique_ptr<>::get() will be valid as long as it hasn't been deleted. It will be deleted, for example, by the destructor of an owning unique_ptr<>. Thus:

    obj*ptr = nullptr;                          // an observing pointer
    { 
      std::unique_ptr<obj> p1;
      {
        std::unique_ptr<obj> p2(new obj);       // p2 is owner
        ptr = p2.get();                         // ptr is copy of contents of p2
        /* ... */                               // ptr is valid 
        p1 = std::move(p2);                     // p1 becomes new owner
        /* ... */                               // ptr is valid but p2-> is not
      }                                         // p2 destroyed: no effect on ptr
      /* ... */                                 // ptr still valid
    }                                           // p1 destroyed: object deleted
    /* ... */                                   // ptr invalid!
    

    Of course, you must never try to use a unique_ptr that has been moved from, because a moved-from unique_ptr has no contents. Thus

    std::unique_ptr<obj> p1(new obj);
    std::unique_ptr<obj> p2 = std::move(p1);
    p1->call_member();                          // undefined behaviour
    
    0 讨论(0)
提交回复
热议问题