Content

Code Snippets

Smart Pointers

Smart pointers help to ensure that programs are free of memory and resource leaks and are exception-safe.

Smart pointers are crucial to the RAII or Resource Acquisition Is Initialialization programming idiom. The main goal of RAII is to give ownership of any heap-allocated resource—for example, dynamically-allocated memory or system object handles—to a stack-allocated object whose destructor contains the code to delete or free the resource and also any associated cleanup code.

In C++11 we have the unique_ptr template to declare a smart pointer local variable (on the stack) based on a specific type of object and initialized with a dynamically allocated object on the heap. As the local variable goes out of scope, due to a function return or thrown exception, automatically the allocated memory on the heap is released.

#include <memory>

unique_ptr<X> a() {
	unique_ptr<X> p(New X);
	return p;
}
void f() {
	unique_ptr<X> p(New X); // create smart pointer
	
	unique_ptr<X> q = a(); // move using moveconstructor
	
	p->dosomething();  // call method
	
	g(*p);  // pass to function
	
	h(p.get()); // pass raw pointer
	
	p.reset(); // free memory explicit
	
} // object pointed to by p automatically destroyed

References



Copyright ©2012 Jacq Krol. All rights reserved. Created July 2012; last updated July 2012.