new로 할당된 개체 수명
new 연산자를 사용하여 할당된 개체는 개체가 정의된 범위가 종료될 때 소멸되지 않습니다. new 연산자는 해당 연산자가 할당한 개체의 포인터를 반환하기 때문에 이들 개체에 액세스하려면 프로그램에서 알맞은 범위의 포인터를 정의해야 합니다. 예를 들면 다음과 같습니다.
// 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 포인터가 예제 범위를 벗어나면 개체를 더 이상 삭제할 수 없습니다.