Boost asio & ssl & error code

Given this code:

const std::size_t rawBufferSize = 1024; char rawBuffer[rawBufferSize] = { 0 }; boost::asio::ssl::stream< boost::asio::ip::tcp::socket >* sslStream; ... // initializing stuff boost::system::error_code ec; auto buffer = boost::asio::buffer(rawBuffer, rawBufferSize); for(; ; ) { int readBytes = sslStream->read_some(buffer, ec); // I know that read_some return std::size_t (unsigned int)... // here, readBytes equals -1 if (ec) break; ... (1) } 

How is it possible that "readBytes" is -1 and the line "(1)" is reached.

Any clue on what I'm doing wrong?

+4
source share
2 answers

In your case, your error_code variable is not a pointer, so the following if statement

 if (ec) break; 

DOES NOT validate if error_code really exists.

You need to do this to check if the error_code file exists:

 if (ec.value() != 0) break; 

Now that an error has occurred, it will break correctly.

The error_code value can be any of these error conditions inside the enum .

+1
source

In error_code.hpp you can find this definition:

 class error_code { ... typedef void (*unspecified_bool_type)(); static void unspecified_bool_true() {} operator unspecified_bool_type() const // true if error { return m_val == 0 ? 0 : unspecified_bool_true; } bool operator!() const // true if no error { return m_val == 0; } ... } 

If you use something like this:

 if (!ec) { // no error } 

you get the right behavior, I hope this is clear. When you call this:

 if (ec) { // error } 

you are actually calling operator unspecified_bool_type() because it returns a pointer (for a function) and can be converted to bool. If there is an error, it returns a pointer to unspecified_bool_true , which is not null. Therefore, it works correctly and does not solve the problem.

+1
source

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


All Articles