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;

displays that string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.136.63