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

时间:2019-06-25 15:18:54

标签: c++ 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:如果将std::move创建为foo,例如const,那么对于const FooPtr& foo = ...会发生什么?

1 个答案:

答案 0 :(得分:3)

  

这里std::move(foo)真的必要吗?

必要,不,有用,是。没有std::move foo是左值,因此将导致复制。那可能是无效的。由于不再需要foo,因此将其移到数组中而不是复制它是有意义的。

  

如果将std::move创建为foo(例如const),const FooPtr& foo = ...会发生什么?

然后您将获得一份副本。您无法移动const,因为移动会更改从对象移出的状态 1

1:从理论上讲,移动可能不需要更改从对象移出的状态,但是无论如何,您只需进行复制即可。