Question

From c++ 11 i can write code without create and deleting raw pointers. But is it the right way to go- Should i always use smart pointers (either shared, unique or weak) or are there situations in which i should delete objects by myself?

Was it helpful?

Solution

It is hard to imagine situations where you would want to manually delete an object, so in that sense, the answer to your question is "yes, always use smart pointers".

However, raw pointers do have another use case. Smart pointers are all about conferring ownership semantics. A unique_ptr has exclusive ownership of the object it points to, and will destroy the object when the pointer goes out of scope. A shared_ptr implements shared ownership, and the object will be destroyed when the last shared pointer goes out of scope.

Raw pointers are still useful for cases where you want to point to an object without indicating any kind of ownership. You're just pointing to an object you know exists, and that someone else (who owns it) will delete it when the time comes.

Raw pointers are for pointing to objects. Smart pointers are for owning objects.

OTHER TIPS

There are really very few cases where you'd want to use a smart pointer. In most applications, either most deletes will be delete this, or if the application is transactional, the transaction manager will take care of the delete. In cases where this doesn't apply, you generally don't want to use dynamic allocation to begin with. About the only times you'll use smart pointers:

  • For some reason or another, you cannot make the object fully operational in the constructor, but have to follow up with additional actions before it is active. In this case, it makes sense to keep it in an std::unique_ptr until the object is fully active, then call release.

  • You really want value semantics, but you also need polymorphism. In this case, use some sort of shared pointer. (But beware of cycles.) If the object is mutable, beware too, since you'll end up with reference semantics.

  • You really want value semantics (with deep copy), but the profiler shows that the cost of copying is too high, you might also consider some sort of shared pointer. This has its dangers, but for large blocks of immutable data, can be a good solution.

But for starters, you should always ask yourself: why am I allocating this object dynamically. The most frequent valid reason is that it is an entity object, with a lifetime defined by program logic (i.e. its lifetime ends as a result of some external event). In such cases, smart pointers will cause more problems than they solve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top