-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSmartPtr1.cpp
More file actions
43 lines (38 loc) · 1.08 KB
/
SmartPtr1.cpp
File metadata and controls
43 lines (38 loc) · 1.08 KB
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
// Простой интеллектуальный указатель с конструктором копирования и перегрузкой оператора присваивания
#include <iostream>
using namespace std;
template <class T> class SmartPtr {
T* ptr; // Фактический указатель
public:
explicit SmartPtr(T* p = NULL) {
ptr = p;
}
SmartPtr(const SmartPtr& S) {
ptr = new T(*S.ptr);
}
SmartPtr& operator=(const SmartPtr& S) {
*ptr = *S.ptr;
return *this;
}
~SmartPtr() {
delete ptr;
}
// Перегрузка оператора разыменования (разадресации)
T& operator*() { return *ptr; }
// Перегрузка оператора селектора выбора
T* operator->() { return ptr; }
};
int main()
{
SmartPtr<int> ptr(new int());
*ptr = 20;
SmartPtr<int> ptr2(ptr);
*ptr2 = 30;
SmartPtr<int> ptr3 = ptr;
*ptr3 = 50;
//ptr = ptr3;
cout << *ptr << " " << *ptr2 << " " << *ptr3;
//cout << *ptr << " " << *ptr3;
//cout << *ptr;
return 0;
}