// Same example programmed with unique_ptr #include #include #include #include "point.h" using namespace std; void f(Point *pp1){ unique_ptrap1(pp1), ap2(new Point(3,4)); // Use unique_ptr in the same way as Point* is used: cout << "ap1: " << *ap1 << endl; // (1,2) cout << "ap2: " << *ap2 << endl; // (3,4) ap2->displace(1,1); cout << "ap2: " << *ap2 << endl; // (4,5) cout << "ap1-ap2 dist: " << ap1->distance_to(*ap2) << endl; // 4.24264 // Destructive copying: The point referred by ap2 is deleted. // The pointer encapsualated in ap1 is moved to ap2. // ap1 is unbound (becomes nullptr). cout << "Now assigning ap1 to ap2" << endl; ap2 = move(ap1); // Short form or ap2 = static_cast&&>(ap1); if (ap1.get()) // ap1 is nullptr cout << "ap1: " << *ap1 << endl; else cout << "ap1 is nullptr" << endl; if (ap2.get()) // (1,2) cout << "ap2: " << *ap2 << endl; else cout << "ap2 is nullptr" << endl; // ap1 and ap2 are deleted on exit from f - out of scope. } int main(){ Point *p = new Point(1,2); // Better to make a smart pointer here, and pass it to p. f(p); // See the exercise! cout << "p: " << *p << endl; // Unsafe! // p has been deleted by exit from f. }