Smart Pointers in C++

Smart pointers are pointers that are deallocated for you, as opposed to having to make sure you 'delete' or 'free' the pointer.

//multiple pointers can point to the same resource
std::shared_ptr<ClassType> pointerName(new ClassType(classParams));
//to create a copy of a shared pointer
std::weak_ptr<ClassType> pointerName = sharedPointerName

//restrict resource to one pointer only, no copies
std::unique_ptr<ClassType> pointerName(new ClassType(classParams));


Smart pointers were introduced in C++11.

using namespace std;

//creating a pointer variable, and allocating memory for it during runtime
shared_ptr<int> newPointer(new int(5));
cout << newPointer; //will print the address in the pointer variable
cout << *newPointer; //dereferencing the pointer to print the value

//no need to call delete on the pointer

< Vectors   |   If Statement >

© 2018 SyntaxDB. All Rights Reserved.