mercredi 15 janvier 2020

reference to std::shared:ptr to avoid reference counting

I am often facing the argument, that by accepting a const std::shared_ptr<T>& one can avoid the reference count increment:

void foo(std::shared_ptr<const int> p); 
void foo2(const std::shared_ptr<const int>& p); 

int main(){
   std::shared_ptr<const int> a;

   foo(a);  // calling this function always does reference counting (atomic locks...)
   foo2(a); // calling this function elides reference counting

   std::shared_ptr<int> b;
   foo2(b); // what happens here? since there is a cast involved creating a temporary ... (NRVO??)
}

But I assume that when calling foo2(b) reference counting is not elided? However, can the compiler or the std-implementation somehow elide reference counting. Would it make it any better if foo2(std::move(b)) would be called, for this elision to happen?

Aucun commentaire:

Enregistrer un commentaire