在 class' 方法中重新分配 *this 是否安全?
Is it safe to reassign *this inside a class' method?
我有一个对象与存储在磁盘上的某个文件相关。对象的构造函数接受这个文件作为参数,读取它并根据文件内容创建一个具有设置的实际对象。在运行期间,该文件有可能被用户修改。该对象有一个方法来检查文件自上次读取后是否已被修改,如果为真,则必须更新该对象。对象内部有足够的成员需要更新,因此与其手动更新每个成员,不如简单地创建一个新对象并将其移动到现有对象中(更少的输入和更好的可读性)更方便。但是像下面的例子那样在方法执行期间更改 *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);
}
}
// ...
}
您似乎担心 this
出现在左侧,尽管 *this = ...
只是调用 operator=
。通常采用右值引用的赋值运算符只是移动成员。
考虑这个更简单的例子:
struct foo {
int x = 42;
foo& operator=(foo&& other){
x = std::move(other.x);
return *this;
}
void bar(){
foo other;
operator=(std::move(other));
}
};
没有错。
另一种让自己相信 *this = std::move(newObject);
没有问题的方法是将所有代码从赋值运算符内联到 update
。对于上面的示例,它将是:
struct foo {
int x = 42;
void bar(){
foo other;
x = std::move(other.x);
}
};
我有一个对象与存储在磁盘上的某个文件相关。对象的构造函数接受这个文件作为参数,读取它并根据文件内容创建一个具有设置的实际对象。在运行期间,该文件有可能被用户修改。该对象有一个方法来检查文件自上次读取后是否已被修改,如果为真,则必须更新该对象。对象内部有足够的成员需要更新,因此与其手动更新每个成员,不如简单地创建一个新对象并将其移动到现有对象中(更少的输入和更好的可读性)更方便。但是像下面的例子那样在方法执行期间更改 *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);
}
}
// ...
}
您似乎担心 this
出现在左侧,尽管 *this = ...
只是调用 operator=
。通常采用右值引用的赋值运算符只是移动成员。
考虑这个更简单的例子:
struct foo {
int x = 42;
foo& operator=(foo&& other){
x = std::move(other.x);
return *this;
}
void bar(){
foo other;
operator=(std::move(other));
}
};
没有错。
另一种让自己相信 *this = std::move(newObject);
没有问题的方法是将所有代码从赋值运算符内联到 update
。对于上面的示例,它将是:
struct foo {
int x = 42;
void bar(){
foo other;
x = std::move(other.x);
}
};