Skip to content

Commit c459970

Browse files
author
Donatien Garnier
committed
Add documentation for shared pointer class
1 parent 3da2ba7 commit c459970

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## Shared Pointer
2+
3+
A shared pointer is a "smart" pointer that retains ownership of an object using
4+
reference counting accross all smart pointers referencing that object.
5+
6+
It is similar to the `std::shared_ptr` class introduced in C++11,
7+
however this is not a compatible implementation (no weak pointer, no make_shared, no custom deleters, etc.)
8+
9+
Usage: `SharedPtr<Class> ptr(new Class())`
10+
11+
When `ptr` is passed around by value the copy constructor and
12+
destructor manages the reference count of the raw pointer.
13+
If the counter reaches zero, `delete` is called on the raw pointer.
14+
15+
To avoid loops, "weak" references should be used by calling the original
16+
pointer directly through `ptr.get()`.
17+
18+
19+
### SharedPtr class reference
20+
21+
[![View code](https://www.mbed.com/embed/?type=library)](https://os-doc-builder.test.mbed.com/docs/development/mbed-os-api-doxy/class_shared_ptr.html)
22+
23+
### Shared pointer example
24+
25+
```cpp
26+
#include "platform/SharedPtr.h"
27+
28+
void test() {
29+
struct MyStruct { int a; };
30+
31+
// Create shared pointer
32+
SharedPtr<MyStruct> ptr( new MyStruct );
33+
34+
// Increase reference count
35+
SharedPtr<MyStruct> ptr2( ptr );
36+
37+
ptr = NULL; // Reference to the struct instance is still held by ptr2
38+
39+
ptr2 = NULL; // The raw pointer is freed
40+
}
41+
```

0 commit comments

Comments
 (0)