How to pass smart pointers the right way  ?

How to pass smart pointers the right way ?

Smart pointers like unique_ptr & smart_ptr help us a lot with automatic memory management and ownership. They do this by adding a wrapper around a normal pointer variable

Cost of a smart pointer
However light weight it may be, yet smart pointers come with a cost. When you need to pass around a shared_ptr as argument of a function, and especially if you're going to do this in a loop for large number of iterations, it does add a cost

So, is there a way to get around this ?? Of Course, Where there is will, there is a way Consider the following code block,

#include <memory>

int main(){
    std::shared_ptr<int> sptr = make_shared<int>(5);
    for(int index = 0; index < 1000; index++)
        another_function(sptr);
}

Purpose of the example to show the use case of a function being called large number of times with a smart pointer as argument. Every single time when the smart pointer is being passed, it does incur a cost.

The way to overcome this is to extract the pointer out of shared_ptr and pass around the extracted pointer in function argument. shared_ptr class provides a method called get which returns the normal pointer from shared_ptr

#include <memory>

int main(){
    std::shared_ptr<int> sptr = make_shared<int>(5);
    int* ptr = sptr.get();
    for(int index = 0; index < 1000; index++)
        another_function(ptr);
}

That all for this nugget, Have a great day ☕

Did you find this article valuable?

Support cppnuggets by becoming a sponsor. Any amount is appreciated!