Smart Pointers in C++
Features:
- unique_ptr: pointed object can be moved, but not copied or shared
Can point to heap object, cannot share
- shared_ptr: pointed object can be shared - it is managed with reference count
Can point to COPY of stack object, can point to heap object and can share
- weak_ptr: Shares, but does not own pointed object
Can point to stack or heap object, but will not permit any operation
Note: auto is now deprecated
unique_ptr:
// Compile: g++ uniqptr.cxx -std=c++0x
#include
#include
using namespace std;
int main()
{
// Declare intPointer as unique pointer -
// auto_ptr inPointer is deprecated
// Pointed object can be moved, not copied or shared
unique_ptr intPointer( new int( 13 ) );
// Prints 13
cout << *intPointer << endl;
// Cannot make another pointer point to unique_ptr: syntax error
// std::unique_ptr newPointer = intPointer;
// Hands off the dynamic memory object to newPointer
unique_ptr newPointer = std::move( intPointer );
// Generates Segmentation fault since intPointer no longer points to memory object
// cout << *intPointer << endl;
// Prints 13
cout << *newPointer << endl;
return 0;
}
shared_ptr and weak_ptr:
// Compile: g++ uniqptr.cxx -std=c++0x
#include
#include
using namespace std;
int main()
{
// Pointer whose pointed object is meant to be shared
// The pointed object is managed with a reference counter
shared_ptr intPointer( new int( 13 ) );
// Prints 13
cout << *intPointer << endl;
// A typical variable
int count = 25;
// Indirect Addressing: sets up a reference counter
shared_ptr anotherPointer;
anotherPointer = make_shared( count );
// Prints 25
cout << *anotherPointer << endl;
// A shared_ptr pointing to another shared_ptr
shared_ptr copyPointer = intPointer;
// Both print 13
cout << *intPointer << endl;
cout << *copyPointer << endl;
// One way to set up a weak pointer
// weak_ptr weakPointer( anotherPointer );
// Shares, but does not own the pointed object
weak_ptr weakPointer = intPointer;
// Syntax error - cannot use typical pointer operations with weak_ptr
// Must create a shared_ptr out of weak_ptr to use it
// cout << *weakPointer << endl;
cout << *intPointer << endl;
// Syntax error - Cannot do this either
// delete weakPointer;
return 0;
}