In my code, there was a typo: instead of using "false"
while initializing a std::string
object, I typed false
(which is a bool
). Now this did not report any compilation error. But later in my code, when this string-object is being used, I get std::logic_error
during runtime. Can anyone please explain, why the construction was allowed in this case (else I would have received a compilation error and found the problem there) ?
Here is a small snippet -
#include <iostream>
int main ()
{
std::string str = false;
std::cout << str << "\n";
}
The o/p that i get while running this -
xhdrdevl8@~/MYBACKUP=>开发者_如何学JAVAg++ -o test_string -g test_string.cxx
xhdrdevl8@~/MYBACKUP=>./test_string
terminate called after throwing an instance of 'std::logic_error'
what(): basic_string::_S_construct NULL not valid
Aborted
std::string
has a constructor that takes a const char*
to a null-terminated string.
false
can be used as a null-pointer constant because it is an integral constant expression with a value of zero, so this std::string
constructor is used.
Passing a null pointer to this constructor yields undefined behavior. Your Standard Library implementation helps you out here by generating a logic_error
exception to inform you that you have violated the constraints of the std::string
constructor by passing it a null pointer. Other implementations may not be so helpful (you might get an immediate crash or data corruption or who knows what).
精彩评论