Bastian
Bastian

Reputation: 1593

C++: Using shared_ptr<...> over raw ptr

I’ve a question regarding the use of shared_ptr<...> over raw ptr. Consider the following example:

shared_ptr<BaseClass> someName = shares_ptr<Derived>(new Derived);
shared_ptr<BaseClass> someName1 = shares_ptr<Derived1>(new Derived1(someName));

Here, Derived1 takes an instance of shared_ptr<BaseClass> as input for it’s constructor. I use shared_ptr mainly for the purpose of polymorphism. Since one BaseClass instance can be used as input for multiple other Derived instance, unique_ptr is not an option because I have to change the ownership all the time.

But ownership is my main concern here. Derived instances doesn’t own the instances passed to the constructors. Is it better to pass a raw ptr?

Upvotes: 0

Views: 118

Answers (1)

Oblivion
Oblivion

Reputation: 7374

If you need to manage ownership of a pointer, as a rule of thumb always prefer unique_ptr over raw pointer. And if you had a reason (i.e. if you share ownership, not transfering ownership with a single owner at a time) prefer shared_ptr over raw pointer.

If you need to use a pointer but not manage its lifetime use shared_ptr for management and weak_ptr for using the pointer without lifetime management.

Still you might find some use cases for raw pointer e.g. in helper functions which requires to be extra cautious to not to generate dangling pointers by accident.

Upvotes: 1

Related Questions