std::move(const shared_ptr 引用) 是什么意思?

eri*_*ric 2 c++ shared-ptr move-semantics c++11 stdmove

以下是我正在尝试的玩具代码...我理解第一个和第二个。第一个将所有权授予_p. 第二个复制p_p. 但第三个我没看懂……

std::move的是什么const shared_ptr &意思?谢谢。

class P { };

class A {
public:
    // first one
    A(std::shared_ptr<P> &p, int) : _p(std::move(p))
    {
        std::cout << "1st Ctor: "
                  << p.use_count() << ", " << _p.use_count() << std::endl;
    }

    // second one
    A(const std::shared_ptr<P> &p, std::string) : _p(p)
    {
        std::cout << "2nd Ctor: "
                  << p.use_count() << ", " << _p.use_count() << std::endl;
    }

    // third one
    A(const std::shared_ptr<P> &p) : _p(std::move(p))
    {
        std::cout << "3rd Ctor: "
                  << p.use_count() << ", " << _p.use_count() << std::endl;
    }

private:
    std::shared_ptr<P> _p;
};

int main()
{
    {
        std::shared_ptr<P> p = std::make_shared<P>();
        A a(p, 1);
        std::cout << "1. body: " << p.use_count() << std::endl;
    }
    std::cout << "-------------" << std::endl;
    {
        std::shared_ptr<P> p = std::make_shared<P>();
        A a(p, "2");
        std::cout << "2. body: " << p.use_count() << std::endl;
    }
    std::cout << "-------------" << std::endl;
    {
        std::shared_ptr<P> p = std::make_shared<P>();
        A a(p);
        std::cout << "3. body: " << p.use_count() << std::endl;
    }
 }
Run Code Online (Sandbox Code Playgroud)

结果是:

$ ./a.out 
1st Ctor: 0, 1
1. body: 0
-------------
2nd Ctor: 2, 2
2. body: 2
-------------
3rd Ctor: 2, 2
3. body: 2
Run Code Online (Sandbox Code Playgroud)

(更新:添加评论以澄清哪个是第一个,第二个等)

son*_*yao 5

std::move只是执行转换并生成 xvalue(右值)。

当传递 a 时const std::shared_ptr<P>,其返回类型将为const std::shared_ptr<P>&&. 然后对于_p(std::move(p))复制构造函数std::shared_ptr(但不是将右值引用指向非 const 的移动构造函数)将被调用,效果与第二种情况相同。

基本上,移动操作倾向于对被移动的对象进行修改;它不应该对const物体起作用。