简体   繁体   English

如何在重载运算符 = 中处理自赋值和异常时释放内存

[英]How memory is getting freed in handling self assignment and Exception in Overloading operator=

I am checking the Operator= overload in Scott Meyers我正在检查 Scott Meyers 中的 Operator= 过载

    Widget& Widget::operator=(const Widget& rhs)
    {
    Bitmap *pOrig = pb; // remember original pb
    pb = new Bitmap(*rhs.pb); // point pb to a copy of rhs’s bitmap
    delete pOrig; // delete the original pb
    return *this;
    }

Suppose the line pb = new Bitmap(*rhs.pb);假设行 pb = new Bitmap(*rhs.pb); // point pb to a copy of rhs's bitmap // 将 pb 指向 rhs 位图的副本

gives some exception(may be due to lack of memory)给出一些异常(可能是由于内存不足)

then i delete pOrig[It will free the memory holded by pOrig and will call Bitmap destructor] So after this,will pb not pointing to a deleted pointer?然后我删除 pOrig[它将释放 pOrig 持有的内存并调用 Bitmap 析构函数] 那么在此之后,pb 不会指向已删除的指针吗?

No. If the new fails, the write to pb doesn't happend, because new throws instead of returning.不。如果new失败,写入pb不会发生,因为new抛出而不是返回。

When you call a function, the function will return a value on a register.当您调用一个函数时,该函数将返回一个寄存器中的值。

So, you get something like:所以,你会得到类似的东西:

call NewBitmap // From within here, you go directly to the catch clause if any
retval -> pb // <<-- this doesn't get executed
delete pOrig // <<-- this doesn't get executed either
*this -> retval // <<-- this either, you don't return, you rethrow as you don't have a catch

Think of this: you will only write to pb once you have a value.想一想:只有在拥有值后,您才会写入 pb。 You'll have a value once NewBitmap returns a value.一旦 NewBitmap 返回一个值,您就会有一个值。 Will not return a value if it throws.如果抛出,则不会返回值。

Anyway, this becomes sort of a rethorical question, because if new fails, it's not a good idea to continue the execution of the program.无论如何,这变成了一个理所当然的问题,因为如果new失败,继续执行程序不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM