-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauto_ptr.cpp
57 lines (49 loc) · 961 Bytes
/
auto_ptr.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <memory>
#include <iostream>
using std::cout;
using std::endl;
// https://softwareengineering.stackexchange.com/questions/291141/how-to-handle-design-changes-for-auto-ptr-deprecation-in-c11
#if __cplusplus >= 201103L
template <typename T>
using auto_ptr = std::unique_ptr<T>;
#else
using std::auto_ptr;
#endif
class MyClass {
public:
MyClass()
{
cout << "I am created" << endl;
}
~MyClass()
{
cout << "I am destroyed" << endl;
}
void DoSomething()
{
cout << "I am doing something" << endl;
}
};
int main()
{
{
MyClass* p(new MyClass);
p->DoSomething();
delete p;
cout << endl;
}
{
auto_ptr<MyClass> p(new MyClass);
p->DoSomething();
cout << endl;
}
{
MyClass* p(new MyClass);
MyClass* q = p;
delete p;
p->DoSomething(); // Watch out! p is now dangling
p = 0; // p is no longer dangling
q->DoSomething(); // Ouch! q is still dangling!
}
return 0;
}