c++ - How does shared_ptr increase counter when passed by value? -


i have sample code below. know little bit rvo (return value optimization) , how copy constructor , assignment operator skipped during optimization , return of value placed directly on memory on left. if shared pointer rvo how shared pointer know when increase counter? because reason thought shared pointer class know when increase counter based on number copies or assignment made.

#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; } 

output:

sp3 count = 1


pass_shared_ptr_by_val: count sp = 2

pass_shared_ptr_by_val: count sp = 3

pass_shared_ptr_by_val: count sp1 = 3


pass_shared_ptr_by_ref: count sp = 1

pass_shared_ptr_by_ref: count sp = 2

pass_shared_ptr_by_ref: count sp1 = 2

~a

if there no copy, nothing needs counted.

if rvo in play no copy made, why ref-count need increased? there no object destroy , decrement ref-count.


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -