Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast in constructors for c++ type

Tags:

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

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

like image 874
G-71 Avatar asked Oct 21 '11 17:10

G-71


1 Answers

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 );
like image 168
Xeo Avatar answered Oct 10 '22 09:10

Xeo