Question

Background

I am writing a multi-threaded, websocket server in C++.

Problem

When I try to integrate my HTTP parser, MKFAHTTPRequest Request( std::string( Buffer ) ); gets completely skipped during execution.

I've cleaned the project and added -Wall and -Werror (which should tell me that Request is an unused variable, but it doesn't).

void operator()(){
    while( true ){
        if( m_Socket->is_open() ){
            char Buffer[1024]; 

            boost::system::error_code Error; 

            std::cout << "MKFAConnection::operator()() - Reading..." << std::endl;
            m_Socket->read_some( boost::asio::buffer( Buffer, sizeof( Buffer ) ), Error ); 

            if( !Error ){
                // This line is getting skipped!?!?!?
                MKFAHttpRequest Request( std::string( Buffer ) );

                m_Socket->write_some( boost::asio::buffer( std::string( "Hello World" ) ) ); 

            } else break; 

        } else break; 

    }

}
Was it helpful?

Solution

MKFAHttpRequest Request( std::string( Buffer ) );

This line doesn't do what you think it does. You think it defines an object named Request of type MKFAHttpRequest and initializes the object with a temporary object of type std::string.

In fact, it declares a function named Request which accepts a single parameter of type std::string and returns an object of type MKFAHttpRequest.

This is related to (or perhaps an example of) the most vexing parse.

Perhaps one of these will make it better:

MKFAHttpRequest Request( (std::string( Buffer )) );
MKFAHttpRequest Request{ std::string( Buffer ) };
MKFAHttpRequest Request = std::string( Buffer );
MKFAHttpRequest Request = MKFAHttpRequest(std::string( Buffer ));

Ref: http://en.wikipedia.org/wiki/Most_vexing_parse

OTHER TIPS

This:

MKFAHttpRequest Request( std::string( Buffer ) );

is as a function declaration in C++. Try this

std::string s( Buffer );
MKFAHttpRequest Request( s );

instead.

Personally, I think the best solution is C++11's uniform initializer syntax:

MKFAHttpRequest Request{ std::string( Buffer ) };

However, an alternative would be simply using static_cast:

MKFAHttpRequest Request( static_cast<std::string>( Buffer ) };

static_cast will find a matching constructor call for std::string, taking char*. It also makes it clear that you are, in effect, "casting" from char* to std::string in order to call the MKFAHttpRequest constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top