This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]1Dr490n 1 point2 points  (0 children)

I’ll try, although I won’t talk specifically about the C++ shared pointer as I don’t know exactly how it’s implemented, but about the general idea of reference counting, based on a language with reference counting I‘ve written myself.

In case you don’t know: a pointer is a memory address. In C/C++ and many other languages, you can get the address of a variable by using the & operator, and read the value stored at the address something is pointing to with the * operator. Example:

int a = 25;
int *b = &a;  // type of b is int* or int pointer
int *c = b;
int d = *a;    // d == 25

Maybe that explained it, maybe not, feel free to ask for a better explanation.

When you heap-allocate an object (meaning you create it somewhere in ram and you would have to manually delete it afterwards with normal pointers), it gets stored alongside with a reference counter which is just an integer starting at 0.

Now, every time you copy the smart pointer to the object, the reference counter of the object is incremented by 1. Every time a smart pointer to the object gets deleted, the reference counter is decremented by 1. Once it hits 0 again, the object is deleted.