生存期对象随新

运算符销毁对象时,它们时定义的范围退出。 由于 运算符返回其分配的指针对象,程序必须定义与适当范围的指针访问这些对象。 例如:

// 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.
}

对于指针 AnotherArray 超出该示例中的范围,对象可能不再被删除。

请参见

参考

新运算符(C++)