我很难理解何时应该使用 const 智能指针以及何时移动它们。
基于以下代码:
class Foo;
class Bar;
typedef std::shared_ptr<Foo> FooPtr;
typedef std::shared_ptr<Bar> BarPtr;
class Bar {
};
class Foo {
public:
static FooPtr create()
{
FooPtr f = std::make_shared<Foo>();
f->initialize();
return f;
}
void setData(const BarPtr& b) {
m_b = b;
}
private:
BarPtr m_b;
};
inline const FooPtr& internalCreateFoo(const BarPtr& b)
{
FooPtr foo = Foo::create();
foo->setData(b);
int id = foo->getID();
m_foos[id] = std::move(foo);
return m_foos[id];
}
1:这里真的有必要使用std::move(foo)
吗?
2:如果 foo
创建为 const
,例如 const FooPtr& foo =,则
?std::move
会发生什么...
最佳答案
is
std::move(foo)
really necessary here?
必要,不,有用,是。如果没有 std::move
foo
是一个左值,因此它将导致复制。这可能是低效的。由于您不再需要 foo
,因此将其移动到数组中而不是复制它是有意义的。
what happens regarding the
std::move
iffoo
is created as aconst
, likeconst FooPtr& foo = ...
?
然后你会得到一份拷贝。您无法移动 const
的内容,因为移动会改变被移动对象的状态1。
1:理论上,移动可能不需要改变被移动对象的状态,但无论如何你只是制作一个拷贝。
关于c++ - Const 正确性、std 移动和智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56757286/