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 string
s managed by ptr
. The type string[]
indicates that the managed memory is a built-in array containing string
s. 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;
displays that string
.