development

const에 대한 포인터 삭제 (T const *)

big-blog 2020. 9. 24. 07:59
반응형

const에 대한 포인터 삭제 (T const *)


const 포인터에 관한 기본적인 질문이 있습니다. const 포인터를 사용하여 상수가 아닌 멤버 함수를 호출 할 수 없습니다. 그러나 나는 const 포인터에서 이것을 할 수 있습니다.

delete p;

이것은 본질적으로 비 상수 '메소드'인 클래스의 소멸자를 호출합니다. 왜 이것이 허용됩니까? 이것을 지원하는 것입니까?

delete this;

아니면 다른 이유가 있습니까?


다음을 지원합니다.

// dynamically create object that cannot be changed
const Foo * f = new Foo;

// use const member functions here

// delete it
delete f;

그러나 문제는 동적으로 생성 된 객체에만 국한되지 않습니다.

{
 const Foo f;
 // use it
} // destructor called here

const 객체에서 소멸자를 호출 할 수 없다면 const 객체를 전혀 사용할 수 없습니다.


이런 식으로 말하십시오- 허용 되지 않았다면 const_cast를 사용하지 않고 const 객체를 삭제할 방법이 없습니다.

의미 상 const는 객체가 불변이어야 함을 나타냅니다. 그러나 객체를 삭제해서는 안된다는 의미는 아닙니다.


생성자와 소멸자는 '메서드'로 간주해서는 안됩니다. 클래스의 객체를 초기화하고 분해하는 특수 구조입니다.

'const pointer'는 객체가 살아있는 동안 작업을 수행 할 때 객체의 상태가 변경되지 않음을 나타냅니다.


const 포인터를 사용하여 상수가 아닌 멤버 함수를 호출 할 수 없습니다.

네, 그렇습니다.

class Foo
{
public:
  void aNonConstMemberFunction();
};

Foo* const aConstPointer = new Foo;
aConstPointer->aNonConstMemberFunction(); // legal

const Foo* aPointerToConst = new Foo;
aPointerToConst->aNonConstMemberFunction(); // illegal

상수가 아닌 개체에 대한 const 포인터를 const 개체에 대한 상수가 아닌 포인터와 혼동했습니다.

라고 한,

delete aConstPointer; // legal
delete aPointerToConst; // legal

여기에 다른 답변에 이미 명시된 이유로 인해 둘 중 하나를 삭제하는 것이 합법적입니다.


그것을 보는 또 다른 방법 : const 포인터의 정확한 의미는 그 또는 다른 포인터 또는 동일한 개체에 대한 참조를 통해 볼 수있는 가리키는 개체를 변경할 수 없다는 것입니다. 그러나 객체가 파괴되면 이전에 삭제 된 객체 차지했던 주소에 대한 다른 모든 포인터 는 더 이상 해당 객체에 대한 포인터가 아닙니다 . 동일한 주소를 저장하지만 해당 주소는 더 이상 객체의 주소가 아닙니다 (실제로 곧 다른 객체의 주소로 재사용 될 수 있음).

This distinction would be more obvious if pointers in C++ behaved like weak references, i.e. as soon as the object is destroyed, all extant pointers to it would immediately be set to 0. (That's the kind of thing considered to be too costly at runtime to impose on all C++ programs, and in fact it is impossible to make it entirely reliable.)

UPDATE: Reading this back nine years later, it's lawyer-ish. I now find your original reaction understandable. To disallow mutation but allow destruction is clearly problematic. The implied contract of const pointers/references is that their existence will act as a block on destruction of the target object, a.k.a. automatic garbage collection.

The usual solution to this is to use almost any other language instead.

참고URL : https://stackoverflow.com/questions/755196/deleting-a-pointer-to-const-t-const

반응형