简体   繁体   English

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

[英]Const correctness, std move and smart pointers

I'm struggling to understand when should I use const smart pointers and when to move them. 我正在努力了解何时应该使用const智能指针以及何时移动它们。

Based on the following code: 基于以下代码:

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: is std::move(foo) really necessary here? 1:在这里真的需要std::move(foo)吗?

2: what happens regarding the std::move if foo is created as a const , like const FooPtr& foo = ... ? 2:如果将foo创建为const (如const FooPtr& foo = ... ,则关于std::move会发生什么?

is std::move(foo) really necessary here? 在这里真的需要std::move(foo)吗?

Necessary, no, useful, yes. 必要,不,有用,是。 Without the std::move foo is an lvalue so it will cause a copy. 没有std::move foo是左值,因此将导致复制。 That can be inefficent. 那可能是无效的。 Since you don't need foo any longer, it makes sense to move it into the array instead of copying it. 由于不再需要foo ,因此将其移到数组中而不是将其复制是有意义的。

what happens regarding the std::move if foo is created as a const , like const FooPtr& foo = ... ? 如果将foo创建为const (如const FooPtr& foo = ... ,则关于std::move会发生什么?

Then you would get a copy. 然后,您将获得一份副本。 You can't move something that is const since moving alters the state 1 of the moved from object. 您不能移动const因为移动会更改从对象移动的状态1

1: In theory a move might not need to alter the state of the moved from object, but then your just making a copy anyways. 1:从理论上讲,移动可能不需要更改从对象移出的状态,但是无论如何,您只需进行复制即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM