This documentation is archived and is not being maintained.

Lifetime of Objects Allocated with new

Objects allocated with the new operator are not destroyed when the scope in which they are defined is exited. Because the new operator returns a pointer to the objects it allocates, the program must define a pointer with suitable scope to access those objects. For example:

// expre_Lifetime_of_Objects_Allocated_with_new.cpp
// C2541 expected
int main()
    // Use new operator to allocate an array of 20 characters.
    char *AnArray = new char[20];

    for( int i = 0; i < 20; ++i )
        // On the first iteration of the loop, allocate
        //  another array of 20 characters.
        if( i == 0 )
            char *AnotherArray = new char[20];

    delete [] AnotherArray; // Error: pointer out of scope.
    delete [] AnArray;      // OK: pointer still in scope.

Once the pointer AnotherArray goes out of scope in the example, the object can no longer be deleted.