小编cli*_*hlt的帖子

在 C++ 中,如果我使用释放析构函数 ~MyClass 引用一个对象,超出范围的引用是否会调用析构函数?

下面的方法总是有效吗?

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会导致析构函数在超出范围时被调用。

c++ scope reference

2
推荐指数
1
解决办法
1159
查看次数

标签 统计

c++ ×1

reference ×1

scope ×1