Exception when passing bool to const std :: string &
Last week I had a funny and thinking moment ... I didn't understand what had happened. Maybe one of you can give me the key.
I wrote a function like this (simplified):
void read(const std::string& sSource, std::string& sResult, bool bCheck = true)
Then later I extended this function with another parameter like this
void read(const std::string& sSource, std::string& sResult, const std::string& sIPAdress, bool bCheck = true)
I forgot to change one function call in my program, so it's called "read":
read("/file/sepp.dat", sResult, false);
As you can see, I passed the link false
to const std::string
.
Yes, the default options are bad, but they are not.
I have an exception (I don't remember the exact output):
"Can't initialize std :: string with nullptr" or so ...
So now there are four questions that I cannot answer on my own:
1.) How can it be that the compiler did not issue a warning about this?
2.) Why can't the type system find, but bool
should never "enter" in string
this way?
3.) Why does this only happen with a parameter const std::string&
and not with std::string&
? (with no const
std::string
compiler error exists)
4.) Is it possible to use pass- bool
to-link const std::string
that makes the compiler think it might be correct?
source to share
1) Implicit conversion from bool
to is allowed const char*
. Unfortunately, this is a feature of the language.
2) Since there is an implicit conversion from bool
to const char*
and std::string
has a constructor that takes const char*
as a parameter. It assumes that it is pointing to a valid null terminated string, which is why you see a runtime error.
3) Since the language does not allow you to bind temporary references to non-const lvalue references. The identifier, however, allows you to bind const lvalue references to temporary ones.
4) The compiler already thinks that this is correct, for all of the above reasons.
source to share