Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing smart-pointer around C++

Tags:

c++

I am currently using C++0x shared_ptr. I have a utility function which needs to take in a pointer to an object and the utility function only perform reading operation from the object and I could be sure that the object still exist when it need to dereference the pointer. I am wondering what is the best practice in passing the smart pointer down to a function like that? Should I pass the smart pointer by reference, by value, or could I get the raw pointer and pass it to the function? Also, which methods give the best performance?

Thanks.

like image 912
Leslie Avatar asked Dec 21 '22 20:12

Leslie


1 Answers

  • pass by value works OK for me
  • pass by reference might be recommended by someone else, but I don't think it's worth it
  • getting the raw pointer and passing it must be done only to interact with legacy code
  • The whole point of SP is that your object will die only if no references on it exist, so if you have an SP at hand it means the pointee is still alive (if shared pointers are used correctly)
like image 92
Armen Tsirunyan Avatar answered Dec 31 '22 01:12

Armen Tsirunyan