voxoid
voxoid

Reputation: 1289

return std::move a class with a unique_ptr member

Why can't I return a class containing a std::unique_ptr, using std::move semantics (I thought), as in the example below? I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr. (I'm using GCC 11.2, C++20)

Example:

#include <memory>

class A {
  public:
    explicit A(std::unique_ptr<int> m): m_(std::move(m)) {}
  private:
    std::unique_ptr<int> m_;
};

A makit(int num) {
    auto m = std::make_unique<int>(num);
    return std::move(A(m));  // error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'x86-64 gcc 11.2 #1
}

int main() {
    auto a = makit(42);
    return 0;
}

I believe the solution is to return a std::unique_ptr, but before I give in I wonder why the std::move approach doesn't work.

Upvotes: 1

Views: 934

Answers (1)

I thought that the return would invoke the move ctor of class A, which would std::move the std::unique_ptr.

All true, but the move constructor only moves the members of A. It cannot move unrelated satellite unique pointers for you.

In the expression A(m), you use m as an lvalue. That will try to copy m in order to initialize the parameter m of A::A (btw, terrible naming scheme for reasoning about all of this). If you move that, i.e. A(std::move(m)), the expression becomes well-formed.

And on that subject, the outer std::move in std::move(A(...)) is redundant. A(...) is already an rvalue of type A. The extra std::move does nothing good here.

Upvotes: 5

Related Questions