DirkMausF
DirkMausF

Reputation: 715

Exception on passing a bool to a const std::string&

Last week I had a funny and thinkable moment... I didn't understand what happened. Maybe someone of you can give me a clue.

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 called "read":

read("/file/sepp.dat", sResult, false);

As you see, I passed a false to a const std::string reference.

Yes, default parameters are bad, but that's not the point here.

I've got an exception (I don't remember the exact output):

"Can't initialize a std::string with a nullptr" or so...

So there are four questions now, that I can't answer myself:

1.) How can it be, that the compiler didn't emit a warning on this?

2.) Why is the type system unable to find out, the a bool should never "go into" a string this way?

3.) Why is this happening only to a const std::string&, not a std::string& parameter? (with a non-const std::string there is a compiler error)

4.) Is there any possible use of passing a bool to a const std::string reference that makes the compiler think, this might be right?

Upvotes: 3

Views: 529

Answers (1)

juanchopanza
juanchopanza

Reputation: 227400

1) An implicit conversion from bool to const char* is allowed. Unfortunately that is a feature of the language.

2) Because there is an implicit conversion from bool to const char* and std::string has a constructor that takes const char* as parameter. It assumes it points to a valid null-terminated string, which is why you see a runtime error.

3) Because the language does not allow to bind temporaries to non-const lvalue references. Id does, however, allow to bind const lvalue references to temporaries.

4) The compiler already thinks it is right, for all the above reasons.

Upvotes: 4

Related Questions