Reputation: 136
Considering 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" equals -1 and the line "(1)" is reached.
Any clue of what I am doing wrong?
Upvotes: 4
Views: 1459
Reputation: 11
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 correct behavior, I hope it's clear. When you call this:
if (ec) {
// error
}
you in fact call operator unspecified_bool_type()
, because it returns a pointer (to function) and that can be converted to bool. If there is an error, it returns pointer to unspecified_bool_true
which is not null. Therefore it works correctly and it won't solve the problem.
Upvotes: 1
Reputation: 63190
In your case, your error_code
variable is not a pointer, so the following if statement
if (ec)
break;
does NOT check correctly if an error_code actually exists.
You need to do this to check as to whether an error_code exists:
if (ec.value() != 0) break;
Now, when an error has occurred, it will break
correctly.
The value of the error_code, can be any of these error conditions, inside the enum
.
Upvotes: 1