以新的配置物件的存留期
物件以配置新運算子便無法損毀時超出所定義的範圍。因為新運算子傳回的指標,它會配置物件時,程式必須定義具有合適的領域,若要存取這些物件的指標。例如:
// 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超出範圍,在範例中,物件不會再被刪除。