Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - pointer passing question

Does somebody have any idead on how to pass boost::shared_ptr - by value or by reference.

On my platform (32bit) sizeof(shared_ptr) equals 8 bytes and it looks like I should pass them by reference, but maybe somebody has another opinion / did a profile / something like that?

like image 576
Yippie-Ki-Yay Avatar asked May 19 '26 07:05

Yippie-Ki-Yay


1 Answers

In C++, it's generally a bad idea to choose whether to pass by value or reference based on the object's size.

Partly because the compiler will often perform copy elision on pass-by-value, negating the cost of copying the value, but mainly because the two options often behave differently.

So choose the option which bests expresses what you need to do.

With a shared_ptr, its entire reason for existing is that it can be copied, so that multiple objects can share ownership of the pointed-to object. If you never pass a shared_ptr by value, you can start wondering why it is a shared_ptr at all. A scoped_ptr may be a more efficient solution then.

Obviously, that's not to say you should always pass shared_ptr's by value either. Just that pass-by-value is a common use case for them.

If you need the caller and callee to have shared ownership, pass by value. If you don't want the callee to take any kind of ownership, pass by reference.

like image 113
jalf Avatar answered May 20 '26 20:05

jalf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!