在类的方法中重新分配 *this 是否安全?

Ale*_*104 9 c++ this-pointer

我有一个与磁盘上存储的某些文件相关的对象。该对象的构造函数接受该文件作为参数,读取它并根据文件内容的设置创建一个实际对象。在运行时该文件有可能被用户修改。该对象有一个方法来检查文件自上次读取以来是否已被修改,如果是这样,则必须更新该对象。对象内部有足够的成员需要更新,因此无需手动更新每个成员,只需创建一个新对象并将其移动到现有对象中会更方便(更少的键入和更好的可读性)。*this但在方法执行期间进行更改实际上是否安全,如下例所示?

void Object::update()
{
    if (this->isModified(file)) // Check if a file has been modified since the last read
    {
        try
        {
            Object newObject(file); // May throw
            *this = std::move(newObject); // Is it safe?
        }
        catch (const std::exception& ex)
        {
            // Invalidate and rethrow exception
            this->invalidate();
            throw(ex);
        }
    }
    // ...
}
Run Code Online (Sandbox Code Playgroud)

for*_*818 8

You seem to be worried about this appearing on the left hand side, though *this = ... merely calls operator=. Typically the assignment operator that takes a rvalue reference just moves the members.

Consider this simpler example:

struct foo {
    int x = 42;
    foo& operator=(foo&& other){
        x = std::move(other.x);
        return *this;
    }
    void bar(){
        foo other;
        operator=(std::move(other));
    }
};
Run Code Online (Sandbox Code Playgroud)

Nothing wrong with that.

Another way to convince yourself that *this = std::move(newObject); is not problematic is to inline all code from the assignment operator to update. For the example above that would be:

struct foo {
    int x = 42;
    void bar(){
        foo other;
        x = std::move(other.x);
    }
};
Run Code Online (Sandbox Code Playgroud)