c++ - what type-conversion is taking place when a boolean value used to construct a string object? -
in code, there typo: instead of using "false" while initializing std::string object, typed false (which bool). did not report compilation error. later in code, when string-object being used, std::logic_error during runtime. can please explain, why construction allowed in case (else have received compilation error , found problem there) ?
here small snippet -
#include <iostream> int main () { std::string str = false; std::cout << str << "\n"; } the o/p while running -
xhdrdevl8@~/mybackup=>g++ -o test_string -g test_string.cxx xhdrdevl8@~/mybackup=>./test_string terminate called after throwing instance of 'std::logic_error' what(): basic_string::_s_construct null not valid aborted
std::string has constructor takes const char* null-terminated string.
false can used null-pointer constant because integral constant expression value of zero, std::string constructor used.
passing null pointer constructor yields undefined behavior. standard library implementation helps out here generating logic_error exception inform you have violated constraints of std::string constructor passing null pointer. other implementations may not helpful (you might immediate crash or data corruption or knows what).
Comments
Post a Comment