作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我们有以下类:
class Foo
{
public:
Foo() { _bar=new Bar };
Foo(const Foo &right) { _bar=new Bar(right.bar); };
Foo(Foo &&right) { _bar=right._bar; right.bar=new Bar(); };
~Foo() { delete _bar; }
Foo &operator=(const Foo &right) { _bar->opertor=(right.bar); return *this;}
Foo &operator=(Foo &&right) { std::swap(_bar, right._bar); return *this;}
void func() { _bar->test=1 };
private:
Bar *_bar;
};
将其更改为以下内容并期望最终用户知道在执行 move 后右值不再有效(因为调用赋值运算符以外的任何东西都可能崩溃)是否合法?
class Foo
{
public:
Foo() { _bar=new Bar };
Foo(const Foo &right) { _bar=new Bar(right.bar); };
Foo(Foo &&right) { _bar=right._bar; right.bar=nullptr; };
~Foo() { if(_bar != nullptr) delete _bar; }
Foo &operator=(const Foo &right)
{
if(_bar == nullptr)
_bar=new Bar();
_bar->opertor=(right.bar);
return *this;
}
Foo &operator=(Foo &&right)
{
if(_bar != nullptr)
delete _bar;
_bar=right._bar;
right._bar=nullptr;
return *this;
}
void func() { _bar->test=1 };
private:
Bar *_bar;
};
我担心的是 func(以及类中的所有其他函数)假设 _bar 存在。
最佳答案
原则上它可能会变得无效,但您可能希望考虑将其保留在可分配状态(您的原始实现,因此编辑,没有这样做)。这将遵循标准库的策略,即:
Unless otherwise specified, all standard library objects that have been moved from are placed in a valid but unspecified state. That is, only the functions without preconditions, such as the assignment operator, can be safely used on the object after it was moved from
我建议重新实现赋值运算符,以便它用新构造的对象交换“this”对象。这通常是避免在执行分配时引入不正确行为的好方法。
关于c++ - move 后右值是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46471243/
我是一名优秀的程序员,十分优秀!