unique-pointers/unique-ptr1.cc - An illustration of unique_ptr<Point> - same example as for raw pointers. | Lecture 4 - slide 12 : 35 Program 5 |
// Same example programmed with unique_ptr #include <memory> #include <iostream> #include <string> #include "point.h" using namespace std; void f(Point *pp1){ unique_ptr<Point>ap1(pp1), ap2(new Point(3,4)); // Use unique_ptr<Point> 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<unique_ptr<Point>&&>(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); f(p); cout << "p: " << *p << endl; // Unsafe! // p has been deleted by exit from f. }