下面的方法总是有效吗?
class MyCLass {
int *pInt;
public:
MyCLass() {
pInt = new int;
*pInt = 42;
}
~MyCLass() {
delete pInt;
printf("Goodbye cruel world!");
}
void func1() {
printf("Hello World %d", *pInt);
}
};
MyCLass foo;
{
MyClass &bar = foo;
//Do stuff
}
foo.func1();
Run Code Online (Sandbox Code Playgroud)
我担心在它的任务中精确模拟原始对象bar会导致析构函数在超出范围时被调用。