Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smart pointers - cases where they cannot replace raw pointers

HI,

I have this query about smart pointers.

I heard from one of my friends that smart pointers can almost always replace raw pointers. but when i asked him what are the other cases where smart pointers cannot replace the raw pointers,i did not get the answer from him.

could anybody please tell me when and where they cannot replace raw pointers?

like image 746
Vijay Avatar asked Apr 07 '10 14:04

Vijay


People also ask

In what kind of circumstances would you use a raw pointer instead of a smart pointer?

The rule would be this - if you know that an entity must take a certain kind of ownership of the object, always use smart pointers - the one that gives you the kind of ownership you need. If there is no notion of ownership, never use smart pointers.

Why are smart pointers better than raw pointers?

Smart pointers are class objects that behave like raw pointers but manage objects that are new and when or whether to delete them— smart pointers automatically delete the managed object at the appropriate time.

Why auto_ptr is deprecated?

Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.


1 Answers

  1. Passing pointers to legacy APIs.
  2. Back-references in a reference-counted tree structure (or any cyclic situation, for that matter). This one is debatable, since you could use weak-refs.
  3. Iterating over an array.

There are also many cases where you could use smart pointers but may not want to, e.g.:

  1. Some small programs are designed to leak everything, because it just isn't worth the added complexity of figuring out how to clean up after yourself.
  2. Fine-grained batch algorithms such as parsers might allocate from a pre-allocated memory pool, and then just blow away the whole pool on completion. Having smart pointers into such a pool is usually pointless.
like image 155
Marcelo Cantos Avatar answered Sep 21 '22 08:09

Marcelo Cantos