c++ - 将 read() 直接用于 C++ std :vector

标签 c++ sockets vector buffer

我正在一些 C++ 中为嵌入式系统封装用户空间 linux 套接字功能(是的,这可能又是在重新发明轮子)。

我想提供一个使用 vector 的读写实现。

编写很简单,我可以通过 &myvec[0] 并避免不必要的复制。我想做同样的事情并直接读入 vector ,而不是读入字符缓冲区然后将所有内容复制到新创建的 vector 中。

现在,我知道我要读取多少数据,并且可以适本地分配(vec.reserve())。我也可以读入 &myvec[0],尽管这可能是一个非常糟糕的想法。显然这样做不允许 myvec.size 返回任何合理的东西。有没有办法做到这一点:

  1. 从安全/C++ 的角度来看并不完全令人讨厌
  2. 不涉及数据 block 的两个拷贝 - 一次从内核到用户空间,一次从 C char * 样式缓冲区到 C++ vector 。

最佳答案

使用 resize() 代替 reserve()。这将正确设置 vector 的大小——之后,&myvec[0] 像往常一样保证指向一个连续的内存块。

编辑:使用 &myvec[0] 作为指向底层数组的指针以进行读写是安全的,并且可以通过 C++ 标准保证工作。 Herb Sutter has to say :

So why do people continually ask whether the elements of a std::vector (or std::array) are stored contiguously? The most likely reason is that they want to know if they can cough up pointers to the internals to share the data, either to read or to write, with other code that deals in C arrays. That’s a valid use, and one important enough to guarantee in the standard.

关于c++ - 将 read() 直接用于 C++ std :vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2780365/

相关文章:

c++ - 单连接服务器套接字

sockets - 使用 phpmyadmin 同步两个数据库 - 此操作的 'socket' 是什么?

c++ - 将 vector 地址分配给迭代器

c++当尾数迭代器时,迭代器+整数的结果是什么?

c++ - 对 vector 中的所有组合求和

c++ - 查看是否安装了adb

c++ - 包含一组自身和自定义比较器的类——循环引用

php - 正确使用 socket_select()

c++ - 不同命名空间中函数的特化

matlab - MATLAB 中的图像卷积 - conv 为什么比我的手写版本快 360 倍?