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()
. But that isn't the case. Why not?
The following code seems to be working fine, which seems equivalent:
std::unique_ptr<int> foo() {
std::unique_ptr<int> p {new int{10}};
return p;
}