On Sunday, 7 June 2015 09:22:45 UTC+3, Stefan Ram wrote:
> You know, all those implicit conversions annoy you
> when they kick in unexpectedly and you only wish that
> that conversion had been defined »explicit«, but ...
>
> then, when you are searching for implicit conversions
> for example purposes, suddenly none comes to your memory?
>
> I am looking for »(in)famous« examples of implicit conversions
> with user-defined types of the C++ standard library.
>
> So far, I remember that
>
> 1st) a char* can be implicitly converted to a ::std::string
>
> and
>
> 2nd) a stream can be implicitly converted to a bool.
>
> It also seems to be possible to implicitly convert a
> double to complex<double> via
>
> constexpr complex(const T& re = T(), const T& im = T());
>
> . Do you remember other simple or famous cases of
> implicit conversions of the standard library?
My first favorite is how 'false' converts to null pointer.
std::string foo()
{
return false;
}
At least compilers have started to warn on that one in recent few years.
Second of my favorite is how implicit conversions screw up the new (too
loose) initialization.
void bar()
{
// a is vector with one element
std::vector<std::string> a{{"hello"}};
// !!! :( !!! b is vector with one undefined behavior element
std::vector<std::string> b{{"hello", "there"}};
// c is vector of three elements
std::vector<std::string> c{{"hello", "there", "kids"}};
}
AFAIK no compiler warns here.
'b' breaks since is it now implicit literal-to-pointer-to-string
conversion or literal-to-pointer-to-iterator conversion?
C++ compiler resolves that ambiguity aggressively and silently and
chooses latter by language rules.
These are quite hard to explain it to novice.