I can't get clang (Apple LLVM version 4.2 (clang-425.0.28)) to compile these classes:
struct A {
int f(){return 2;}
};
class Cl{
std::unique_ptr<A> ptr;
public:
Cl(){ptr = std::unique_ptr<A>(new A);}
Cl(const Cl& x) : ptr(new A(*x.ptr)) { }
Cl(Cl&& x) : ptr(std::move(x.ptr)) { }
Cl(std::unique_ptr<A> p) : ptr(std::move(p)) { }
void m_ptr(std::unique_ptr<A> p){
ptr = std::unique_ptr<A>(std::move(p));
}
double run(){return ptr->f();}
};
I would like to run the constructor as follows:
std::unique_ptr<A> ptrB (new A);
Cl C = Cl(ptrB);
but if I do this I get the following compiler error: ../src/C++11-2.cpp:66:10: error: call to implicitly-deleted copy constructor of 'std::unique_ptr' C.m_ptr(ptrB);
I can solve the compiler problem by running Cl(std::move(ptrB))
but this doesn't actually move the ownership of A away from ptrB: I can still run ptrB->f()
without causing a run-time crash... Secondly, the constructor is not very satisfying, since I want to hide the implementation of std::move
in the class interface.
Thanks in advance.