0

A simple question, is it legal to use an object, which owns a unique pointer, after it was moved, and continue working with the unique pointer in case it wasn't moved?

Basic Coder
  • 10,882
  • 6
  • 42
  • 75

1 Answers1

2

The standard guarantees that a moved-from unique_ptr does compare equal to nullptr. N4659 [unique.ptr]/4:

Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold:

  • (4.1) u2.p is equal to the pre-transfer u.p,
  • (4.2) u.p is equal to nullptr, and
  • (4.3) if the pre-transfer u.d maintained state, such state has been transferred to u2.d.

These guarantees also imply that it's safe to move from one that's already been moved from.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I failed to find this description in N4741... http://eel.is/c++draft/unique.ptr#4 – songyuanyao Apr 24 '18 at 01:07
  • @songyuanyao It is phrased differently but amounts to the same thing – 1201ProgramAlarm Apr 24 '18 at 01:09
  • @1201ProgramAlarm But it doesn't say the `unique_ptr` being moved from will be set to `nullptr` explicitly. – songyuanyao Apr 24 '18 at 01:13
  • 4
    @songyuanyao In N4741, this is guaranteed via the Postconditions for the move constructor, move assignment, and move-like constructor and assignment from a different specialization. For example, the constructor `unique_ptr(unique_ptr&& u) noexcept;` has a postcondition `u.get() == nullptr`. – aschepler Apr 24 '18 at 01:33
  • @aschepler feel free to edit my post to include the post-C++17 wording changes – M.M Apr 24 '18 at 01:37