簡體   English   中英

Boost asio&ssl&錯誤代碼

[英]Boost asio & ssl & error 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)
}

“ readBytes”等於-1並到達“(1)”行的可能性如何。

我做錯了什么線索嗎?

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 (!ec) {
    // no error
}

您得到正確的行為,希望這很清楚。 當您致電:

if (ec) {
    // error
}

您實際上調用了operator unspecified_bool_type() ,因為它返回了一個指向函數的指針,並且可以將其轉換為bool。 如果有錯誤,它將返回指向unspecified_bool_true指針,該指針unspecified_bool_true為null。 因此,它可以正常工作,並且不能解決問題。

就您而言,您的error_code變量不是指針,因此以下if語句

if (ec)
   break;

無法正確檢查error_code是否實際存在。

您需要執行以下操作來檢查是否存在error_code:

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

現在,當發生錯誤時,它將正確break

error_code的值可以是enum任何這些錯誤條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM