我在使用 asio::streambuf 时遇到过问题,希望有人能告诉我我是否错误地使用了该类。当我运行此示例代码时,它会出现段错误。为什么?
让事情变得更加困惑的是,这段代码适用于 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;
}
最佳答案
我使用和看到 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));
我不确定为什么您的代码不起作用,但如果上面的代码确实起作用,那么单步执行它可能会显示出与您的代码的一些差异。还有它在哪条线上崩溃?
关于c++ - 使用 boost::asio::streambuf 的代码导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4971980/