#include #include using namespace std; template struct Box; template Box make_box(Args&&... x); template struct Box { private: T* ptr{nullptr}; Box(T* n) : ptr{n} {} // private constructor public: Box() {} ~Box() { if (ptr) delete ptr; } T& operator *() { return *ptr; } T* operator ->() { return ptr; } /* Box(Box&& other) { // move constructor ptr = other.ptr; other.ptr = nullptr; } */ T* release() { T* temp = ptr; ptr = nullptr; return temp; } template // required to recognize derived classes Box(Box&& b) { ptr = static_cast(b.release()); } // move constructor template Box& operator =(Box&& other) { // move = operator if (this == (Box*)&other) return *this; // prevents x = move(x); if (ptr) delete ptr; ptr = static_cast(other.release()); return *this; } // explicitly delete copy semantics Box(const Box& b) = delete; Box& operator =(const Box& b) = delete; template static Box New(Args&&... args) { return Box(new T(forward(args)...)); } template friend Box make_box(Args&&... x); }; template Box make_box(Args&&... args) { return Box(new T(std::forward(args)...)); } struct A { virtual int f() = 0; }; struct B : A { int f() override { return 1; } }; struct C : A { int f() override { return 2; } }; struct D { Box b; //unique_ptr b; }; int main() { Box a = Box::New(4); Box b = Box::New(6); *b = 9; a = move(b); cout << *a << endl; unique_ptr au = make_unique(); Box c =make_box(8); Box s = Box::New(); Box t = make_box(); s = move(t); s = Box::New(); //Box s2 = Box::New(); Box S[] = {Box::New(), Box::New()}; for(auto& b:S) cout << b->f() << endl; D d1; D d2; d1 = move(d2); return 0; }