Share via


新しいによって割り当てられたオブジェクトの有効期間

新規作成 の演算子によって割り当てられたオブジェクトはその型が定義されているスコープが終了すると破棄されません。 新規作成 の演算子によって割り当てられたオブジェクトへのポインターを返すためプログラムはこれらのオブジェクトにアクセスするには適切なスコープのポインターを定義する必要があります。次に例を示します。

// 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++)