gpt4 book ai didi

c++ - move 后右值是否有效?

转载 作者:太空狗 更新时间:2023-10-29 23:29:45 25 4
gpt4 key购买 nike

假设我们有以下类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com