C++11的shared_ptr任务

C++11's shared_ptr assignment

本文关键字:ptr 任务 shared C++11      更新时间:2023-10-16

我有以下代码:

    #include <memory>
    int main(void)
    {
        std::shared_ptr<int> currInt(nullptr);
        std::shared_ptr<int> newInt(new int);
        currInt = newInt;
        return 0;
    }

这在c++ 11中是无效的(在草案版本中是有效的),赋值构造函数现在使用move语义。有些事我不明白。

谁能解释一下我如何修改上面的代码使它…工作吗?

shared_ptr的复制构造函数,否则shared_ptr有什么意义?

OP的clang链接是说,如果只定义了move赋值操作符,那么复制构造函数将被隐式删除,使shared_ptr不能正确地。这也可以在Boost更改集中看到,其中显式添加了复制赋值操作符以纠正错误。

您可以在§20.7.2.2.3[util.smartptr.shared.assign]/1—3中找到shared_ptr的复制赋值操作符。

shared_ptr& operator=(const shared_ptr& r) noexcept;
template<class Y> shared_ptr& operator=(const shared_ptr<Y>& r) noexcept;
template<class Y> shared_ptr& operator=(auto_ptr<Y>&& r);