6

asio :: streambufの使用で問題が発生しましたが、クラスを誤って使用しているかどうかを誰かに教えてもらいたいと思っています。このサンプルコードを実行すると、segfaultsになります。なんで?

さらに混乱させるために、このコードはWindows(Visual Studio 2008)では機能しますが、Linux(gcc 4.4.1では)では機能しません。

#include <boost/asio.hpp>
using namespace std;

int main()
{
        boost::asio::streambuf Stream;

        // Put 4 bytes into the streambuf...
        int SetValue = 0xaabbccdd;
        Stream.sputn(reinterpret_cast<const char*>(&SetValue), sizeof(SetValue));

        // Consume 3 of the bytes...
        Stream.consume(3);
        cout << Stream.size() << endl; // should output 1

        // Get the last byte...
        char GetValue;
        // --------- The next line segfaults the program ----------
        Stream.sgetn(reinterpret_cast<char*>(&GetValue), sizeof(GetValue));
        cout << Stream.size() << endl; // should output 0

        return 0;
}
4

1 に答える 1

1

私が asio::streambuf を使用して見た方法は、通常、std::ostream または std::istream を使用したもので、次のようなものです。

boost::asio::streambuf Stream;
std::ostream os(&Stream);
int SetValue = 0xaabbccdd;
os.write(reinterpret_cast<const char*>(&SetValue), sizeof(SetValue));

コードが機能しない理由はわかりませんが、上記が機能する場合は、ステップスルーすると、コードとの違いがわかる場合があります。また、どの行でクラッシュしていますか?

于 2011-03-07T03:39:29.880 に答える