为什么在任务后打电话给攻击函数

Why is the destructor called after assignment?

本文关键字:攻击 函数 打电话 任务 为什么      更新时间:2023-10-16

为什么在线路mystring = "Hello, there!";之后在这里打电话给destructor这还不是它远离范围。我绝对错过了C 的一些怪癖!

我知道该行调用默认复制构造函数,在复制构造函数返回后总是调用destructor?

作为旁注,我正在使用C 03,否C 11。

编辑:另外,请注意,我知道以下程序导致的双重删除。我在这里实验。只是想引起您的注意。

class MyString
{
private:
    char* mystring;
    int m_length;
public:
    MyString(const char* str="")
    {
        assert(str);
        m_length = strlen(str) + 1;
        mystring = new char[m_length];
        for (int i = 0; i < m_length; ++i)
            mystring[i] = str[i];
        mystring[m_length-1] = '';
    }
    ~MyString()
    {
        delete[] mystring;
    }
};
int main()
{
   MyString mystring("");
   mystring = "Hello, there!";
   cout << "Destructor not yet called ";
}

,因为您没有类的分配操作员,该操作员将字符串字面的 mystring = "Hello, there!";转变为3份操作。

  • 首先,它必须从字符串文字中构造一个临时对象。

  • 然后,它将该临时性使用并与默认副本(PRE C 11(/MOVE(post C 11(如果未另行删除((分配操作员为类生成的编译器。

  • 然后必须销毁其创建的临时对象。这就是为什么您会在该表达式结束时看到对破坏者的呼叫。


请注意,由于临时对象在

之后被破坏
mystring = "Hello, there!";

现在删除了指针mystring所持的,您无法再访问它。当它被销毁时,它也会导致双重删除,这是不确定的行为并会导致并发症。