Boost::asio what is this kind of strange coding style?

I am about to debug something within my boost asio socket communication. And found this piece of code inside of the asio library (found in boost/asio/impl/write.hpp line 169 (boost 1.47) ):

  switch (start)
  {
    case 1:
    buffers_.prepare(this->check_for_completion(ec, total_transferred_));
    for (;;)
    {
      stream_.async_write_some(buffers_,
          BOOST_ASIO_MOVE_CAST(write_op)(*this));
      return; 
    default:
      total_transferred_ += bytes_transferred;
      buffers_.consume(bytes_transferred);
      buffers_.prepare(this->check_for_completion(ec, total_transferred_));
      if ((!ec && bytes_transferred == 0)
          || buffers_.begin() == buffers_.end())
        break;
    }

    handler_(ec, static_cast<const std::size_t&>(total_transferred_));
  }

I have already a lot of years of C/C++ development experience, but never ever in my life I saw such kind of weird implementation. Look there, the default: label of the switch statement is within the for loop.

If I understand this right, then the switch statement is "misused" instead of a goto, right (for the cases where start != 1, goto default:)? Is it actually a valid C/C++ with respect to the standard? What will happen if I for example put

for(int i=0; i < 10; i++)

instead of the for loop in the original code. Will "i" be undefined in case when jump is performed to default: label? Sure I might use a debugger here, however this seems so suspicious for me, that I think this could produce different behavior for different compilers.


This is well-defined, valid code. A switch really is a glorified goto . For some clever use of this construct, take a look at Duff's device.

As for your for , that wouldn't be legal. A jump to a case label can't cross an initialization.


它似乎是达夫设备的一个版本。

链接地址: http://www.djcxy.com/p/82290.html

上一篇: 互斥量在boost regex构造函数中声明

下一篇: Boost :: asio这种奇怪的编码风格是什么?