我有一个关于const指针的基本问题.我不允许使用const指针调用任何非const成员函数.但是,我可以在const指针上执行此操作:
delete p;
Run Code Online (Sandbox Code Playgroud)
这将调用类的析构函数,它实质上是一个非const'方法'.为什么允许这样做?它只是支持这个:
delete this;
Run Code Online (Sandbox Code Playgroud)
还是有其他原因吗?
考虑一下
class Foo
{
public:
Foo(){}
~Foo(){}
void NonConstBar() {}
void ConstBar() const {}
};
int main()
{
const Foo* pFoo = new Foo();
pFoo->ConstBar(); //No error
pFoo->NonConstBar(); //Compile error about non const function being invoked
delete pFoo; //No error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在main函数中,我调用了Foo的const和非const函数
试图调用任何非const函数会在Visual Studio中产生错误,就像这样
error C2662: 'Foo::NonConstBar' : cannot convert 'this' pointer from 'const Foo' to 'Foo &'
但delete pFoo不会发出任何此类错误.delete语句必然会调用没有const修饰符的Foo类的析构函数.析构函数也允许调用其他非const成员函数.那么它是一个const函数吗?或者是在const指针上删除一个特殊的异常?
我知道const在C++ 中使用一个方法意味着一个对象通过该方法是只读的,但它可能仍然会改变.
但是,此代码显然通过const引用(即通过const方法)更改对象.
这段代码在C++中是否合法?
如果是这样:它是否打破const了类型系统的性质?为什么/为什么不呢?
如果没有:为什么不呢?
#include <iostream>
using namespace std;
struct DoBadThings { int *p; void oops() const { ++*p; } };
struct BreakConst
{
int n;
DoBadThings bad;
BreakConst() { n = 0; bad.p = &n; }
void oops() const { bad.oops(); } // can't change itself... or can it?
};
int main()
{
const BreakConst bc;
cout << bc.n << endl; // 0
bc.oops(); // O:) …Run Code Online (Sandbox Code Playgroud)