Search code examples
c++move

C++ use after move: Valid use-case?


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?


Solution

  • 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.