Unique_ptr: A Smart Pointer
A smart pointer can be used to perform the delete automatically. C++ smart pointers are defined in the memory header.
/* * This program shows how to use the c++11 unique_ptr object to automatically * delete created objects. */ #include <iostream> #include <string> #include <memory> using namespace std; class Fred { public: Fred(string s, int a) { m_val = a; m_lab = s; } int val() { return m_val; } string lab() { return m_lab; } unique_ptr<Fred> combine(unique_ptr<Fred> &other) { return unique_ptr<Fred>(new Fred(lab()+","+other->lab(), val()+other->val())); } private: int m_val; string m_lab; }; int main() { unique_ptr<Fred> f1(new Fred("skunk", 41)); unique_ptr<Fred> f2(new Fred("wombat", 33)); cout << f1->lab() << ": " << f1->val() << endl; cout << f2->lab() << ": " << f2->val() << endl; unique_ptr<Fred> f3 = f1->combine(f2); cout << f3->lab() << ": " << f3->val() << endl; }

This small example shows the use of unique_ptr, an type of smart pointer. A smart pointer is a class whose objects behave like pointers, but have additional capabilities which make them “smart”. Smart pointers are suited to different situations; unique_ptr is designed for the situation here, where an object is allocated, referred to throughout its life by one pointer, then deleted.

Unique pointer is a template class like others in the C++ libraries, and its type parameter is the type it points to. Its constructor takes a plain pointer, usually the result of a new, then behaves as though it were the pointer itself. In particular, the * and -> operators operate the same. But the pointer object is responsible to run delete on behalf of the user. In the case of unique_ptr, the object pointed to is deleted when the pointer itself ceases to exist, usually at a closing curly brace.

Unique pointer object may not be assigned (except to NULL), and cannot be copied. If you try these operations, your program will not compile. You can “move” one smart pointer to another with notation like this: A = move(B);, which will delete whatever A points to (unless it's NULL), make A point to where B did, and make B NULL. Afterward, A is responsible to delete the object it points to (that B used to).

Passing a unique_ptr is usually best done by reference, as shown here. Passing using default parameter rules involves a copy, and will fail on the compile. A unique_ptr can be sent using the move utility, but that will NULL the sending pointer.