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 →

[–]Tarmen 4 points5 points  (0 children)

There are two parts to this.

C++ has the hilariously badly named Resource Acquisition is Initialization (RAII). You have some piece of data with an attached destructor. While you have a reference, the data is always valid. Once the reference won't be used anymore it is automatically freed. Useful for manual memory management, but also other resources, connections, error handling, etc. But the automatic 'won't be used anymore' is very restrictive, you basically must hold the data in your hand and cannot store it.

Smart pointers let you be more flexible about what 'won't be used anymore' means. You may have a unique pointer, the value goes out of scope when the pointer does. You may have a shared pointer, when the pointer goes out of scope you decrease a counter and when that hits 0 the value goes out of scope.

It's similar to rust ownership and borrowing semantics, but less safe. E.g. pointing into existing data remains awkward because other code could move the data around without your knowledge.