C++ Smart Pointers

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  • std::shared_ptr<ClassType> variableName = std::make_shared<ClassType>(arg1, arg2, ...);
  • std::shared_ptr<ClassType> variableName (new ClassType(arg1, arg2, ...));
  • std::unique_ptr<ClassType> variableName = std::make_unique<ClassType>(arg1, arg2, ...); // C++14
  • std::unique_ptr<ClassType> variableName (new ClassType(arg1, arg2, ...));

Remarks

C++ is not a memory-managed language. Dynamically allocated memory (i.e. objects created with new) will be "leaked" if it is not explicitly deallocated (with delete). It is the programmer's responsibility to ensure that the dynamically allocated memory is freed before discarding the last pointer to that object.

Smart pointers can be used to automatically manage the scope of dynamically allocated memory (i.e. when the last pointer reference goes out of scope it is deleted).

Smart pointers are preferred over "raw" pointers in most cases. They make the ownership semantics of dynamically allocated memory explicit, by communicating in their names whether an object is intended to be shared or uniquely owned.

Use #include <memory> to be able to use smart pointers.



Got any C++ Question?