【发布时间】:2011-02-11 17:14:39
【问题描述】:
我在使用 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::streambuf表现出相同的行为? -
我也得到了核心转储。请
#include <iostream>编译代码。 -
Clang on OS X Mavericks 编译并运行成功,产生
1\n0\n作为输出。 -
我也遇到过同样的问题。我用 clang++ 而不是 g++ 编译了我的程序,一切都按预期工作。
标签: c++ boost boost-asio streambuf