vendredi 30 septembre 2016

Returning member unique_ptr from class method

I am trying to return a std::unique_ptr class member (trying to move the ownership) to the caller. The following is a sample code snippet:

class A {
 public:
  A() : p {new int{10}} {}

  static std::unique_ptr<int> Foo(A &a) {
    return a.p; // ERROR: Copy constructor getting invoked
    // return std::move(a.p); WORKS FINE

  }
  std::unique_ptr<int> p;
};

I thought the compiler (gcc-5.2.1) would be able to do return value optimization (copy elision) in this case without requiring the explicit intent via std::move() to be coded. Please explain.

Also, the following code seems to be working fine:

std::unique_ptr<int> foo() {
  std::unique_ptr<int> p {new int{10}};
  return p;
}

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire