In the final part, we will take a look at custom deleters and pass the smart pointers to functions,
Smart pointers have the default deleter but also a custom deleter can be utilized. It brings about some overhead such as increasing the size. We know the std::unique_ptr size is equal to raw’s pointer size. if a custom deleter is used the size of unique_ptr increases but, it depends on the kind of custom deleters such as no-capture lambdas (stateless), std::function object, etc…
The way of creating safely smart pointers: make_shared and make_unique don’t accept custom deleters.
Here is the example to show overheads and custom deleters using methods:
Passing Smart Pointers:
When we pass to smart-pointers as a function parameter we need to know some details. According to C++ Core Guidelines, there are a few rules that we should know.
Firstly, we will realize passing the unique_ptr as a function parameter.
If we use unique_ptr, probably, we need uniqueness. And uniqueness means at the std::unique_ptr can not be copied as well shared. For establishing uniqueness, the function needs to take std::unique_ptr’s reference or directly its object.
inside Pass Pointer Function: planet no:10
inside Pass Reference Function: planet no:10
inside embeddedWorld Destructor: planet No: 10
inside Pass Function before the reset: planet no20
inside embeddedWorld Destructor: planet No: 20
after the -pass- function plane no:15
inside embeddedWorld Destructor: planet No: 15
Any function which is taking a parameter as a unique_ptr reference may call the unique_ptr reset function like the pass function at the code above. If functions only use unique_ptr’s pointer It can take a reference and pointer, like the passSourcePointer and passReferencePointer functions.
When we pass the shared_ptr to functions we have to make sure its lifetime, whether it’s shared or not, whether reference count is increased or retained, etc. There is no best way to pass shared_ptr. The way depends on our purpose. Let’s check the ways on examples.
inside the share function: use_count:2
after the share function, use_count: 1
inside the reseat function: use_count:1
after the reseat function, value: 20
inside the mayShare function: use_count:1
According to the code above:
The function ‘void share(std::shared_ptr<int> i)’ takes a shared_ptr as a value. Inside the function, the copy constructor is invoked, then the reference count is increased. The overhead is sharing ownership with copy instructions. It extends the lifetime.
The function ‘void reseat(std::shared_ptr<int> & i)’ takes a shared_ptr as a non-const reference. The reference count is not increased. The function can reset the shared pointer.
The functions ‘void mayShare(const std::shared_ptr<int>& i)’ takes a const shared ptr as a reference. It’s the same as taking the object’s pointer or reference.