Skip to content

Commit d0a5393

Browse files
author
Amanda Butler
authored
Merge pull request #671 from donatieng/shared_ptr
Add documentation for shared pointer class
2 parents c2e1133 + 37aa27a commit d0a5393

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
## Shared Pointer
2+
3+
A shared pointer is a "smart" pointer that retains ownership of an object by using reference counting accross all smart pointers referencing that object.
4+
5+
It is similar to the `std::shared_ptr` class introduced in C++11. However, this is not a compatible implementation, as there are no weak pointers, no `make_shared`, no custom deleters, and so on.
6+
7+
Usage: `SharedPtr<Class> ptr(new Class())`
8+
9+
When `ptr` is passed around by a value, the copy constructor and destructor manage the reference count of the raw pointer. If the counter reaches zero, `delete` is called on the raw pointer.
10+
11+
12+
### SharedPtr class reference
13+
14+
[![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)
15+
16+
### Shared pointer example
17+
18+
```
19+
#include "platform/SharedPtr.h"
20+
21+
void test() {
22+
struct MyStruct { int a; };
23+
24+
// Create shared pointer
25+
SharedPtr<MyStruct> ptr( new MyStruct );
26+
27+
// Increase reference count
28+
SharedPtr<MyStruct> ptr2( ptr );
29+
30+
ptr = NULL; // Reference to the struct instance is still held by ptr2
31+
32+
ptr2 = NULL; // The raw pointer is freed
33+
}
34+
```

0 commit comments

Comments
 (0)