Effective Modern C++:shared_ptr

shared_ptr is a pointer allowed to be copied, it is like the normal pointer we use, but it’s smart for its counting function.

A normal pointer is not safe as when we are deleting it, we don’t know if someone else is using it. The shared_ptr count the users of this pointer, when someone release the pointer, its count will decrement, the memory block where it points will release only when the count becomes 0, which means no one is using it.

Initialize a shared_ptr:

shared_ptr<int> s{ new int{3} };

It can also be “made”, even made directly from value:

int normalInt = 5;
shared_ptr<int> madePtr = make_shared<int>(normalInt);
shared_ptr<int> madePtr2 = make_shared<int>(1);//from number

It can be copied and moved, when it is copied, its count increments:

shared_ptr<int> m = move(s);
shared_ptr<int> k = m;
long count = k.use_count();//count is now 2

Its release function is reset:

k.reset();
count = k.use_count();//count is now 1

What’s more, it supports customer delete, when you want to do some additional deleting work except deleting the pointer itself, you may need it. The customer delete function will be called only when the user count is 0:

struct V
{//Our object
	int* v;
	V()
	{
		v = new int[100];
	}
};
void deleteV(V* vPtr)
{//Our customer delete function
	delete vPtr->v;
}
shared_ptr<V> newV{ new V(),deleteV};//customer delete as para
shared_ptr<V> oldV = newV;//copied once, count is now 2
oldV.reset();//deleteV will not be called now, as count is 1
newV.reset();//deleteV will now be called, count is 0

It doesn’t support array!

Wangxin -->

Wangxin

I am algorithm engineer focused in computer vision, I know it will be more elegant to shut up and show my code, but I simply can't stop myself learning and explaining new things ...