Search code examples
c++11move-semanticsunique-ptrorder-of-execution

Moving a unique_ptr in the same statement it is used


Is doing something like this safe? I'm unsure if the execution order is guaranteed or not.

auto foo = std::make_unique<Foo>();
foo->Bar(std::move(foo));

Solution

  • It will work fine.

    The sequence:

    1. Evaluate std::move(foo) then evaluate foo-> (or the other way around, which does not matter as neither changes the state of the foo pointer).
    2. Invoke Foo::Bar(...) on the target object obtained in #1 passing the rvalue-casted foo also obtained in #1.

    Probably not the cleanest code style.