Skip to content

Commit e8889d8

Browse files
committed
better weak pointer explanation
1 parent 982c1f6 commit e8889d8

1 file changed

Lines changed: 19 additions & 1 deletion

File tree

content/posts/cpp-for-cscharp.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,9 @@ What makes this one different from the other smart pointers:
178178
- there can be many weak pointers per object
179179
- weak pointers dont increase the amount of shares like a shared pointer
180180
- weak pointers dont own an object so the object's lifetime is not tied to the weak ptr
181-
- all weak pointers expire (points to nullptr) when the last shared ptr gets dropped
181+
- all weak pointers expire when the last shared ptr gets dropped
182+
- weak pointers dont point to anything directly, so you cant simply deref them
183+
- to use a weak pointer you must convert it to a temporary shared pointer
182184

183185
```cpp
184186
// cpp
@@ -196,6 +198,22 @@ void test()
196198
// get amount of shares
197199
int shares = sp.use_count(); // still 1, weak ptr didnt add a share
198200

201+
// directly dereferencing a weak pointer wont work
202+
// *wp and wp-> cause a compile time error
203+
// to use a weak pointer you must convert it to a temp shared pointer
204+
// lock creates a shared pointer if the object still exists otherwise a nullptr
205+
auto temp_sp = wp.lock()
206+
if (temp_sp != nullptr)
207+
{
208+
// safe to use *temp_sp or temp_sp->
209+
210+
// while the temporary shared pointer exists there is an extra share
211+
int shares = sp.use_count(); // now 2 temporarily
212+
213+
// drop temp shared pointer
214+
temp_sp.reset();
215+
}
216+
199217
// destroy the only and last shared pointer with ownership
200218
sp.reset();
201219

0 commit comments

Comments
 (0)