c++ - 删除指向 const (T const*) 的指针

标签 c++ constants delete-operator

我有一个关于 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 对象。

关于c++ - 删除指向 const (T const*) 的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/755196/

相关文章:

c++ - 在 pthread_create() 中使用局部变量作为参数是否有效?

c++ - std::auto_ptr<T> 用法

c++ - 为什么这个析构函数不必删除类对象?

delphi - 我不应该将接口(interface)作为 const 传递吗?

c++ - =delete 有哪些用途?

c++ - 为什么将对象地址存储在缓冲区中会在实例化和删除它们时导致内存泄漏?

c++ - 使用可变函数/宏简化工作

C++ 默认参数构造函数与内联初始化优先级

c++ - std::function 作为 & 发送的(非)const 输入参数

c++ - 引用指针错误 : Non-const lvalue reference "const * FooBarClass" cannot bind to a temporary