按值传递时shared_ptr如何增加计数器?

sol*_*lti 2 c++ smart-pointers shared-ptr rvo

我在下面有此示例代码。我对RVO(返回值优化)以及如何在优化过程中跳过复制构造函数和赋值运算符一无所知,而返回值则直接放在左侧的内存中。因此,如果RVO共享了指针,共享指针如何知道何时增加其计数器?因为某种原因,我认为共享指针类会根据复制的数量或分配的数量知道何时增加计数器。

#include <iostream>
#include <memory>
using namespace std;
class A{
public:
    A(){}
    A(const A& other){ std::cout << " Copy Constructor " << std::endl; }
    A& operator=(const A&other){
        std::cout << "Assingment operator " <<  std::endl;        
        return *this;
    }    
    ~A(){
        std::cout << "~A" <<  std::endl;
    } 
};

std::shared_ptr<A> give_me_A(){
    std::shared_ptr<A> sp(new A);
    return sp;
}

void pass_shared_ptr_by_val(std::shared_ptr<A> sp){

    std::cout << __func__ << ": count  sp = " << sp.use_count() << std::endl;
    std::shared_ptr<A> sp1 = sp;
    std::cout << __func__ << ": count  sp = " << sp.use_count() << std::endl;
    std::cout << __func__ << ": count sp1 = " << sp1.use_count() << std::endl;
}

void pass_shared_ptr_by_ref(std::shared_ptr<A>& sp){
    std::cout << __func__ << ": count  sp = " << sp.use_count() << std::endl;  
    std::shared_ptr<A> sp1 = sp;
    std::cout << __func__ << ": count  sp = " << sp.use_count() << std::endl;
    std::cout << __func__ << ": count sp1 = " << sp1.use_count() << std::endl;
}

int main(){

    {
        shared_ptr<A> sp3 = give_me_A();

        std::cout << "sp3 count = " << sp3.use_count() << std::endl;
        pass_shared_ptr_by_val(sp3);
        pass_shared_ptr_by_ref(sp3);
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

sp3计数= 1


pass_shared_ptr_by_val:计数sp = 2

pass_shared_ptr_by_val:计数sp = 3

pass_shared_ptr_by_val:计数sp1 = 3


pass_shared_ptr_by_ref:计数sp = 1

pass_shared_ptr_by_ref:计数sp = 2

pass_shared_ptr_by_ref:计数sp1 = 2

〜A

Jes*_*uhl 6

如果没有副本,则无需计数。

如果正在播放RVO,则不会复制,那么为什么需要增加引用计数?没有多余的对象可以破坏和减少引用计数。

  • *如果*复印,则参考数量会增加。如果使用RVO,则不会进行复制,并且引用计数不会增加。就那么简单。 (3认同)