我搜索了这个问题的答案,却找不到答案.请考虑以下代码:
struct Foo
{
int *bar;
Foo(int barValue) : bar(new int(barValue)) {}
~Foo() { do_this(); }
void do_this() { delete bar; bar = nullptr; }
};
int main()
{
const Foo foo(7);
}
Run Code Online (Sandbox Code Playgroud)
do_this()不能在一个const对象上调用,所以我做不了类似的事情foo.do_this().在某些情况下do_this(),在析构函数之外调用也是有意义的,这就是为什么我不想简单地在析构函数定义中包含代码.因为do_this()修改成员变量,我不能将其声明为const.
我的问题是:将析构函数可以调用do_this()一个在const当对象被销毁的对象?
我尝试了它并没有收到任何错误,但我想确保一旦我的程序终止,我不会导致内存泄漏.
C++标准说修改最初声明的对象const是未定义的行为.但那么构造函数和析构函数如何运作?
class Class {
public:
Class() { Change(); }
~Class() { Change(); }
void Change() { data = 0; }
private:
int data;
};
//later:
const Class object;
//object.Change(); - won't compile
const_cast<Class&>( object ).Change();// compiles, but it's undefined behavior
Run Code Online (Sandbox Code Playgroud)
我的意思是构造函数和析构函数与调用代码完全相同,但是允许它们更改对象并且不允许调用者 - 他会遇到未定义的行为.
它应该如何在实施和标准下工作?
This question is different from:
I wrote a class Test like this.
class Test {
private:
int *p;
public:
//constructor
Test(int i) {
p = new int(i);
}
Test & operator = (const Test &rhs) {
delete p;
p = new int(*(rhs.p));
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
When the parameter rhs of the operator function is itself (i.e. …