Reputation: 67319
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?
Upvotes: 11
Views: 1489
Reputation: 41351
It would be quite hard to implement smart pointers if at some point you don't use plain pointers.
I suppose it would also be harder to implement certain data structures with smart pointers. E.g freeing the memory of a regular linked list is quite trivial, but it would take some thought to figure out the combination of owning and non-owning smart pointers to get the same result.
Upvotes: 1
Reputation: 300439
It's a matter of semantics:
For example:
class FooContainer
{
public:
typedef std::vector<Foo> foos_t;
foos_t::const_iterator fooById(int id) const; // natural right ?
};
But you expose some implementation detail here, you could perfectly create your own iterator class... but iterator usually means incrementable etc... or use a pointer
class FooContainer
{
public:
const Foo* fooById(int id) const;
};
Possibly it will return NULL
, which indicates a failure, or it will return a pointer to an object, for which you don't have to handle the memory.
Of course, you could also use a weak_ptr
here (you get the expired
method), however that would require using shared_ptr
in the first place and you might not use them in your implementation.
Upvotes: 3
Reputation: 186118
There are also many cases where you could use smart pointers but may not want to, e.g.:
Upvotes: 11
Reputation: 6208
Depends on the smart pointer you use. std::auto_ptr is not compatible with STL containers.
Upvotes: 3
Reputation: 100748
If you have a situation where a raw pointer is cast to an intptr_t and back for some reason, it cannot be replaced by a smart pointer because the casting operation would lose any reference counting information contained in the smart pointer.
Upvotes: 1
Reputation: 14004
interaction with legacy code. if the api needs a raw pointer you need to provide a raw pointer even if once its in your code you wrap it in a smart pointer.
Upvotes: 2