top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C++: What is a smart pointer and when should I use one?

0 votes
546 views
C++: What is a smart pointer and when should I use one?
posted Sep 18, 2018 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

I am sharing my views on the smart pointers based on my experience with them so far.

I have used three type of smart pointers so far for the different purposes.

  1. shared pointer - use a shared pointer only when there is a requirement to share the ownership of the created objected. For example one function created an objected using shared pointer and passed that pointer to some other function using some mechanism and exit from its execution stack. The created shared pointer can still be used by other functions as it is shared pointer.

  2. Unique pointer - use when you know only one pointer can point to the object. When the unique pointer is created then it can be moved to another unique pointer but can't be copied. That means only one pointer can point to the object at most.

  3. weak pointer - use when a function just want to access a shared pointer object but don't want to hold the owner-ship of the object. That means there is no role of weak pointer in the object destruction. Whenever the weak pointer want to access the object it takes lock and if lock is successful that means the pointed object still exists and it uses.

If you see all above types are pointer but there are doing extra things compare to the raw pointer which just stores the object address. That is the reason all above pointers comes under the category of smart pointers.

answer Oct 2, 2020 by Crazy
...