Roddy
Roddy

Reputation: 68033

Why don't smart pointers have conversion operator back to the base pointer?

If often find myself using code like this:

boost::scoped_ptr<TFoo> f(new TFoo);

Bar(f.get());  // call legacy or 3rd party function : void Bar (TFoo *)

Now, I think the smart pointers could easily define an implicit conversion operator back to the 'raw' pointer type, which would allow this code to still be valid, and ease the 'smartening' of old code

Bar(f);

But, they don't -or at least, not the ones I've found. Why?

Upvotes: 2

Views: 714

Answers (2)

jcoder
jcoder

Reputation: 30035

Because it's then very easy to accidentally bypass the smart pointer. For example what if you write :-

delete f;

In your example, bad things would happen. Your functions could be similar, they might store their own copy of the pointer which breaks the smart pointer then. At least calling get forces you to think "is this safe?"

Upvotes: 2

Nim
Nim

Reputation: 33655

IMO implicit conversion is the root of all evil in c++, and one the toughest kinds of bugs to track down.

It's good practice not to rely on them - you can't predict all behaviours.

Upvotes: 7

Related Questions