2

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?

Roddy
  • 66,617
  • 42
  • 165
  • 277

2 Answers2

7

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.

Nim
  • 33,299
  • 2
  • 62
  • 101
  • That may be true, but without an example or two it's not (yet) very helpful. – Roddy Dec 04 '12 at 12:34
  • @Roddy, did you read the link posted by BoBTFish? I can give a simple example, I spent a long time in our current codebase trying to figure out why a standard math function (`fmod()`) failed to report the fractional quantity held in a simple structure wrapping a double. The code called `fmod()` with the structure, and the compiler reported no error. Reason it turned out in the end was that the type had an implicit conversion to `int` and to make matters worse, it was always rounding up! Now that operator has been erased from the type, compiler throws up errors everywhere... – Nim Dec 04 '12 at 12:38
  • ...which are easy to find and replace with a `get()` to return the double value held in the type. It may sound like a simple solution to start with, but due to the way that implicit conversions can happen between types (say `int` to `bool` [and vice versa]), it's always a safe approach not to do it. – Nim Dec 04 '12 at 12:40
  • yes, read and understood. Thanks for the example. My point really is that if I mindlessly append `.get()` then I'm in a worse position than before: I've just bloated the code and added a false sense of smart-pointer-derived security. Obviously each `.get()` needs looking at on its merits, but knowing the 'smells' to watch for will help. – Roddy Dec 04 '12 at 13:17
2

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?"

jcoder
  • 29,554
  • 19
  • 87
  • 130