小编ln *_* vv的帖子

C++ 中 `delete this` 和 `this->~Obj` 之间的区别

当我编写一个演示字符串类时,在复制赋值函数中,我尝试在复制之前通过“删除此”来清除自身。但它失败了。

    Str &operator=(const Str &s) {
        if (this != &s) {  // self-assignment check
            //delete this; //cannot run as I imagine
            this->~Str();  
            _size = s._size;
            _str = new char[_size + 1];
            memcpy(_str, s._str, _size + 1);
        }
        return *this;
    }
    ~Str() {
        _size = 0;
        delete[] _str;
    }
Run Code Online (Sandbox Code Playgroud)

linux 告诉我的

双释放或损坏(出)中止(核心转储)

c++ memory-management double-free assignment-operator delete-operator

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