-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweak_ptr.cpp
More file actions
34 lines (27 loc) · 827 Bytes
/
weak_ptr.cpp
File metadata and controls
34 lines (27 loc) · 827 Bytes
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
#include <iostream>
#include <memory>
class MyClass {
public:
void DoSomething() {
std::cout << "Doing something...\n";
}
};
int main() {
std::weak_ptr<MyClass> weak;
{
std::shared_ptr<MyClass> shared = std::make_shared<MyClass>();
weak = shared;
if(auto sharedFromWeak = weak.lock()) {
sharedFromWeak->DoSomething(); // Safely use the object
std::cout << "Shared uses count: " << sharedFromWeak.use_count() << '\n'; // 2
}
}
// shared goes out of scope and the MyClass object is destroyed
if(auto sharedFromWeak = weak.lock()) {
// This block will not be executed because the object is destroyed
}
else {
std::cout << "Object has been destroyed\n";
}
return 0;
}