简体   繁体   English

Boost asio&ssl&错误代码

[英]Boost asio & ssl & error code

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. “ readBytes”等于-1并到达“(1)”行的可能性如何。

Any clue of what I am doing wrong? 我做错了什么线索吗?

In error_code.hpp you can find this definition: error_code.hpp您可以找到以下定义:

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. 您实际上调用了operator unspecified_bool_type() ,因为它返回了一个指向函数的指针,并且可以将其转换为bool。 If there is an error, it returns pointer to unspecified_bool_true which is not null. 如果有错误,它将返回指向unspecified_bool_true指针,该指针unspecified_bool_true为null。 Therefore it works correctly and it won't solve the problem. 因此,它可以正常工作,并且不能解决问题。

In your case, your error_code variable is not a pointer, so the following if statement 就您而言,您的error_code变量不是指针,因此以下if语句

if (ec)
   break;

does NOT check correctly if an error_code actually exists. 无法正确检查error_code是否实际存在。

You need to do this to check as to whether an error_code exists: 您需要执行以下操作来检查是否存在error_code:

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

Now, when an error has occurred, it will break correctly. 现在,当发生错误时,它将正确break

The value of the error_code, can be any of these error conditions, inside the enum . error_code的值可以是enum任何这些错误条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM