unique_ptr to a Built-In Array

You can also use a unique_ptr to manage a dynamically allocated built-in array. For example, consider the statement

unique_ptr< string[] > ptr( new string[ 10 ] );

which dynamically allocates an array of 10 strings managed by ptr. The type string[] indicates that the managed memory is a built-in array containing strings. When a unique_ptr that manages an array goes out of scope it deletes the memory with delete [] so that every element of the array receives a destructor call.

A unique_ptr that manages an array provides an overloaded [] operator for accessing the array’s elements. For example, the statement

ptr[ 2 ] = "hello";

assigns "hello" to the string at ptr[2] and the statement

cout << ptr[ 2 ] << endl; ...

Get C++11 for Programmers, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.