![]() ![]() ![]() ![]() | An illustration of auto_ptr<Point>. | Lecture 3 - slide 12 : 36 Program 2 |
#include <memory> #include <iostream> #include <string> #include "point.h" using namespace std; void f(Point *pp1){ auto_ptr<Point>ap1(pp1), ap2(new Point(3,4)); // Use auto_ptr<Point> like Point* cout << "ap1: " << *ap1 << endl; // (1,2) cout << "ap2: " << *ap2 << endl; // (3,4) ap2->move(1,1); cout << "ap1-ap2 dist: " << ap1->distance_to(*ap2) << endl; // 4.24264 // Destructive copying: ap2 is deleted // ap2 becomes a pointer to ap1 // ap1 is unbound (corresponding to NULL). ap2 = ap1; if (ap1.get()) // ap1 is NULL !!! cout << "ap1: " << *ap1 << endl; else cout << "ap1 is NULL" << endl; if (ap2.get()) // (1,2) cout << "ap2: " << *ap2 << endl; else cout << "ap2 is NULL" << endl; // ap1 and ap2 are deleted on exit from f // ap2 refers to pp1, which therefore is deleted. } int main(){ Point *p = new Point(1,2); f(p); cout << "p: " << *p << endl; // Unsafe! // p has been deleted by f. }