c++ - Const 正确性、std 移动和智能指针

标签 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:如果 foo 创建为 const,例如 const FooPtr& foo =,则 std::move 会发生什么...

最佳答案

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:理论上,移动可能不需要改变被移动对象的状态,但无论如何你只是制作一个拷贝。

关于c++ - Const 正确性、std 移动和智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56757286/

相关文章:

c++ - 计算 char 的 ascii 值之和

c++ - 适合按顺序插入的容器? C++

c++ - 智能指针和数组

C++:从文件中读取?

c++ - 测量可执行文件的数据和指令缓存的大小

c++ - 从智能指针获取所有权,并通过同一智能指针进一步访问原始指针

c++ - 传递 unique_ptr<T> 的 C++ vector 而不传递所有权

c++ - 智能指针和 vector C++ 的多态性问题

c++ - 我应该如何重构这个事件处理代码?

c++ - 在什么情况下,现代编译器不能对函数应用 NRVO 优化?