Удаление указателя на константу (T константа*)

Если я вас хорошо понял, вам просто нужно использовать HTML button в вашем «цвете шрифта» div


Вот ваш пример (проверено в Chromium): https://jsfiddle.net/3abnh4uj/1/

Надеюсь, что эта помощь или, по крайней мере, направит вас в правильном направлении:)

82
задан Sam 17 August 2014 в 14:22
поделиться

4 ответа

Поддерживается:

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

Если Деструкторы не могут быть вызваны для константных объектов, мы не можем использовать константные объекты вообще.

103
ответ дан Agnel Kurian 24 November 2019 в 09:13
поделиться

Скажем так - если бы не было разрешено, не было бы никакого способа удалить const объекты без использования const_cast.

Семантически const является признаком того, что объект должен быть неизменным. Это не означает, однако, что объект не должен быть удален.

45
ответ дан PaulJWilliams 24 November 2019 в 09:13
поделиться

Конструкторы и деструкторы не должны рассматриваться как «методы». Это специальные конструкции, которые инициализируют и разрушают объект класса.

«Указатель констант» означает, что состояние объекта не изменится, когда с ним будут выполняться операции, пока он жив.

5
ответ дан Indy9000 24 November 2019 в 09:13
поделиться

Another way to look at it: the precise meaning of a const pointer is that you will not be able to make changes to the pointed-to object that would be visible via that or any other pointer or reference to the same object. But when an object destructs, all other pointers to the address previously occupied by the now-deleted object are no longer pointers to that object. They store the same address, but that address is no longer the address of any object (in fact it may soon be reused as the address of a different object).

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.

5
ответ дан 24 November 2019 в 09:13
поделиться
Другие вопросы по тегам:

Похожие вопросы: