You are viewing...

Dabbling in C++, Modern Way of Pointers (Raw, Unique, Shared, Weak)

Updated on September 11, 2016 at the 14th hour
Posted under:

DISCLAIMER: All views are considered my own and you should not draw any conclusions on associates.

I am going to assume you know what pointers are for and why you use them. If not, please go learn about stack and heap memory.

If you are like me, you know raw pointers look like this: `int * someNumber`. You manage your own memory with `new` and `delete`. Manual memory management has its' benefits, but clearly it does not at a large scale given the amount of overhead people are willing to take to use garbage collected languages.

If you know about auto_ptr, forget about it. It is gone in C++17.

Unique, Shared and Weak Pointers are the new memory management for C++, so semi-automatic garbage collection! Basically ARC from Objective-C though Boost may have been the inspiration for both. All of these pointers require the <memory> header. There is a link below for the C++ memory reference.

Unique pointer works in that you assign an owner (scope) to the pointer. When we exit from that scope, then the pointer and its' contents are freed.

How do I use it? There are two ways to instantiate this guy:
  1. std::unique_ptr uptr(new Object());
  2. std::make_unique<Object>(args...);
Shared pointer is reference counting for pointers. I expect this to be heavily used. The reference counts are incremented for each assignment whereas decremented when the assignees are no longer assignees. When the count reaches zero then the point and its' contents are freed.

How do I use it? Same way as unique.
  1. std::shared_ptr sptr(new Object());
  2. std::make_shared<Object>(args...);
Weak pointer is exactly what you think it is. It can point to other objects, but has no effect on whether the object is freed or not.

How do I use it?
  1. std::weak_ptr<Object> wptr = sptr;

 

This is your friendly Intro to Modern C++ pointers. Stop using raw pointers. :) Use the link below as your bible.

Links
  1. CPP Memory Ref: http://en.cppreference.com/w/cpp/memory
You just read "Dabbling in C++, Modern Way of Pointers (Raw, Unique, Shared, Weak)". Please share if you liked it!
You can read more recent posts here.