c++ - 使用 boost::asio::streambuf 的代码导致段错误

标签 c++ boost boost-asio streambuf

我在使用 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/

相关文章:

c++ - 我不明白异步操作如何使 HTTP 服务器并发

c++ - boost::async_write 导致数据损坏

C++栈变量和堆变量

c++ - 如何为引用参数定义模板函数和为指针参数定义相同的函数

c++ - boost 1.46.1 中的 boost::asio::windows::stream_handle 在哪里?

c++ - 在多线程场景中提升 asio async_receive_from 缓冲消息

C++继承循环依赖

c++ - OS X Lion 上的 libplist 编译错误 : string. h not found

c++ - 模板:模板函数不能很好地与类的模板成员函数配合使用

c++ - 如何从析构函数(在多线程环境中)正确取消 Boost deadtime_timer?