更优雅的方式使用recv()和向量< unsigned char> [英] A more elegant way to use recv() and vector<unsigned char>

查看:240
本文介绍了更优雅的方式使用recv()和向量< unsigned char>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有这个代码示例:

So far, I have this code sample:

...
int nbytes =0;
vector<unsigned char> buffer;
buffer.resize(5000);
nbytes = recv(socket, &buffer[0], buffer.size(),0);
//since I want to use buffer.size() to know data length in buffer I do
...
buffer.resize(nbytes);

这是另一种方式,知道缓冲区中的数据长度,而不使用resize因为不可能将数据接收到未被调整为适当大小的向量。我认为reserve()方法不做分配,根据C ++的STL文档。另一个问题:使用这种技术是内存泄漏安全吗?

Is it some another way, to know data length in buffer without using resize() twice? Because it is not possible to receive data into vector that is not resized to proper size. I think reserve() method don't do allocation, according to the C++ STL documentation. And another question: is using this kind of technique is memory leak-safe ?

推荐答案

这种技术是安全的,并优选。使用 std :: vector 是在C ++中实现可变长度缓冲区的推荐方式。

This technique is leak-safe, quite clean and preferable. Using std::vector is the recommended way of implementing a variable-length buffer in C++.

不是所有的数据都适合向量 - 没有问题,只是调整到更大的大小,并传递跟随已经填充部分的部分的地址。

If you find that not all data fits into the vector - no problem, just resize it to bigger size and pass the address of the section that follows the already-filled part.

使用 reserve()不是一个很好的主意 - 它不影响 size()返回,所以你会失去方便,并且可能不会获得任何优势。

Using reserve() is not a very good idea - it doesn't affect what size() returns, so you will lose convenience and likely will gain no advantages.

这篇关于更优雅的方式使用recv()和向量&lt; unsigned char&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆