常量正确性、标准移动和智能指针

Const correctness, std move and smart pointers

我很难理解什么时候应该使用 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 被创建为 conststd::move 会发生什么情况,例如 const FooPtr& foo = ...?

is std::move(foo) really necessary here?

有必要,没有,有用,有。没有 std::move foo 是一个左值,所以它会导致复制。那可能是低效的。由于您不再需要 foo,因此将其移入数组而不是复制它是有意义的。

what happens regarding the std::move if foo is created as a const, like const FooPtr& foo = ...?

然后你会得到一份。您不能移动 const 的东西,因为移动会改变被移动对象的状态 1

1: 理论上移动可能不需要改变被移动对象的状态,但是无论如何你只是复制一个。