Most questions on Stackoverflow are asking about shared_ptr should be passed by ref or by value. However my question is exampled like this:
class Foo;
void function1(Foo & ff) { ff.m_abc = 1024; }
void function2(const std::shared_ptr<Foo> & ff) { ff->m_abc = 1024; }
The function1
and function2
may use and change some part of ff.
My case here:
I have a need for calling a function with an arg *this
or shared_from_this()
.
print(msg, *this);
or
print(msg, this->shared_from_this());
I can either use function1
or function2
style in my code for a function.
However, if I use function2
style, I need to implement Foo
to inherit from std::enable_shared_from_this
, but with function1
style, I do not need to.
I'm using this function in a single-threaded environment
Pass the shared_ptr by value. This invokes the copy constructor, increments the reference count, and makes the callee an owner. There's a small amount of overhead in this operation, which may be significant depending on how many shared_ptr objects you're passing.
Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another. A shared_ptr is a container for raw pointers.
The difference is that std::make_shared performs one heap-allocation, whereas calling the std::shared_ptr constructor performs two.
It is a reference counting ownership model i.e. it maintains the reference count of its contained pointer in cooperation with all copies of the std::shared_ptr. So, the counter is incremented each time a new pointer points to the resource and decremented when destructor of the object is called.
You only pass the shared_ptr
to a function if the function cares about there being a shared_ptr
, usually because it wants to keep a copy, or a weak_ptr
.
Anything else just reduces applicability of the function for no gain.
You should pass a shared_ptr
if you want to share the ownership of the object with the function you're calling, that is if you want to make sure the object will be alive as long as the function needs it.
One case where this is important is if your function does an asynchronous operation, it might want to use your object once the operation is finished and by that time your object might have been deleted so if you passed by reference, that reference is dangling, while if you passed shared_from_this()
, you are guaranteed that the life time of your object will be extended to as long as the function needs it. (Most code samples of boost::asio
for example are based on this logic).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With