相关疑难解决方法(0)

删除指向const的指针(T const*)

我有一个关于const指针的基本问题.我不允许使用const指针调用任何非const成员函数.但是,我可以在const指针上执行此操作:

delete p;
Run Code Online (Sandbox Code Playgroud)

这将调用类的析构函数,它实质上是一个非const'方法'.为什么允许这样做?它只是支持这个:

delete this;
Run Code Online (Sandbox Code Playgroud)

还是有其他原因吗?

c++ const delete-operator

83
推荐指数
5
解决办法
2万
查看次数

析构函数被认为是const函数吗?

考虑一下

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指针上删除一个特殊的异常?

c++ destructor

22
推荐指数
2
解决办法
3136
查看次数

这段代码是否颠覆了C++类型系统?

我知道const在C++ 中使用一个方法意味着一个对象通过该方法是只读的,但它可能仍然会改变.

但是,此代码显然通过const引用(即通过const方法)更改对象.

这段代码在C++中是否合法?

如果是这样:它是否打破const了类型系统的性质?为什么/为什么不呢?

如果没有:为什么不呢?

注1:我对这个例子进行了一些编辑,所以答案可能是指旧的例子.

编辑2:显然你甚至不需要C++ 11,所以我删除了那个依赖.

#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)

c++ const const-correctness pointer-aliasing

20
推荐指数
1
解决办法
809
查看次数