2011-02-11 138 views
5

我遇到過使用asio :: streambuf的問題,並且希望有人可以告訴我,如果我錯誤地使用了類。當我運行這個示例代碼時,它會出現段錯誤。爲什麼?使用boost :: 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; 
} 
+0

可能的錯誤... – niXman 2011-02-12 08:51:04

+0

這只是`asio :: streambuf`,或者`std :: streambuf`表現出相同的行爲嗎? – 2011-02-18 15:32:16

回答

1

我已經使用和ASIO看到::流緩衝通常使用的方法是使用的std :: ostream的或std :: istream的,是這樣的:

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

我不知道爲什麼你的代碼無法正常工作,但如果上述功能正常工作,則通過它可能會顯示與您的代碼不同的一些區別。還有哪條線路崩潰?

相關問題