Embedding constructors for type C ++

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; } 

Result: 1 Why? When I use the -Wall flag, compiler write warning: address 'std :: string s2 (std :: string) will always evaluate to' 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; } 

Result: ddd

This is a normal result.

+6
source share
1 answer

The most annoying parsing .

 std::string s2( std::string( s1 ) ); 

parsed as declaring a function that takes the std::string parameter with the name s1 and returns std::string ". Then you try to print this function, which first converts it to a function pointer (normal decay / conversion rule). Since operator<< of std::ostream not overloaded for function pointers at all, it will try to convert to bool, which will succeed, and since the function pointer is non-zero, it will be 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 ); 
+13
source

Source: https://habr.com/ru/post/899811/


All Articles