Skip to content

Commit be4e427

Browse files
committed
Add unique_ptr, weak_ptr and unique_ptr
1 parent 4f1d1f2 commit be4e427

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,42 @@ N::T t; // Use name T in namespace N
303303
using namespace N; // Make T visible without N::
304304
```
305305

306+
## `memory` (dynamic memory management)
307+
308+
```cpp
309+
#include <memory> // Include memory (std namespace)
310+
shared_ptr<int> x; // Empty shared_ptr to a integer on heap. Uses reference counting for cleaning up objects.
311+
x = make_shared<int>(12); // Allocate value 12 on heap
312+
shared_ptr<int> y = x; // Copy shared_ptr, implicit changes reference count to 2.
313+
cout << *y; // Deference y to print '12'
314+
if (y.get() == x.get()) { // Raw pointers (here x == y)
315+
cout << "Same";
316+
}
317+
y.reset(); // Eliminate one owner of object
318+
if (y.get() != x.get()) {
319+
cout << "Different";
320+
}
321+
if (y == nullptr) { // Can compare against nullptr (here returns true)
322+
cout << "Empty";
323+
}
324+
y = make_shared<int>(15); // Assign new value
325+
cout << *y; // Deference x to print '15'
326+
cout << *x; // Deference x to print '12'
327+
weak_ptr<int> w; // Create empty weak pointer
328+
w = y; // w has weak reference to y.
329+
if (shared_ptr<int> s = w.lock()) { // Has to be copied into a shared_ptr before usage
330+
cout << *s;
331+
}
332+
unique_ptr<int> z; // Create empty unique pointers
333+
unique_ptr<int> q;
334+
z = make_unique<int>(16); // Allocate int (16) on heap. Only one reference allowed.
335+
q = move(z); // Move reference from z to q.
336+
if (z == nullptr){
337+
cout << "Z null";
338+
}
339+
cout << *q;
340+
```
341+
306342
## `math.h`, `cmath` (floating point math)
307343

308344
```cpp

0 commit comments

Comments
 (0)