I have the following c++ code:
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
const std::string s1 = "ddd";
std::string s2( std::string( s1 ) );
std::cout << s2 << std::endl;
}
The result is: 1 Why? When I use -Wall flag, compiler write warning: the address of ‘std::string s2(std::string)’ will always evaluate as ‘true’
But this code:
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
const std::string s1 = "ddd";
std::string s2( ( std::string )( s1 ) );
std::cout << s2 << std::endl;
}
The result: ddd
It's normal result
Most-vexing-parse.
std::string s2( std::string( s1 ) );
is parsed as the declaration of a "function taking a std::string
parameter named s1
and returning a std::string
". You then try to print that function, which will first convert it to a function pointer (normal decay/conversion rule). Since the operator<<
of std::ostream
isn't overloaded for function pointers in general, it will try a conversion to bool, which succeeds, and since the function pointer is nonnull, it's converted to the boolean value true
, which is printed as 1
.
Change it to
std::string s2( (std::string( s1 )) );
or even better, just
std::string s2( s1 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With