本文介绍了将read()直接使用到C ++ std:vector中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个嵌入式系统的某些C ++中包装了用户空间的linux socket功能(是的,这可能是重新发明轮子)。

I'm wrapping up user space linux socket functionality in some C++ for an embedded system (yes, this is probably reinventing the wheel again).

使用向量提供读写实现。

I want to offer a read and write implementation using a vector.

写操作很容易,我可以通过& myvec [0] code>并避免不必要的复制。我想做同样的事情,直接读入一个向量,而不是读入一个字符缓冲区,然后复制到一个新创建的向量。

Doing the write is pretty easy, I can just pass &myvec[0] and avoid unnecessary copying. I'd like to do the same and read directly into a vector, rather than reading into a char buffer then copying all that into a newly created vector.

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

Now, I know how much data I want to read, and I can allocate appropriately (vec.reserve()). I can also read into &myvec[0], though this is probably a VERY BAD IDEA. Obviously doing this doesn't allow myvec.size to return anything sensible. Is there any way of doing this that:


  1. 从安全/ C ++的角度来看,并不完全感觉到幸运

  2. 不涉及数据块的两个副本 - 一次从内核到用户空间,一次从C char * 样式缓冲区到C ++向量。 li>
  1. Doesn't completely feel yucky from a safety/C++ perspective
  2. Doesn't involve two copies of the data block - once from kernel to user space and once from a C char * style buffer into a C++ vector.


推荐答案

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

Use resize() instead of reserve(). This will set the vector's size correctly -- and after that, &myvec[0] is, as usual, guaranteed to point to a continguous block of memory.

编辑:使用& myvec [0] 作为指向读写基础数组的指针是安全和有保证的以C ++标准工作。这里是Herb Sutter的: / p>

Using &myvec[0] as a pointer to the underlying array for both reading and writing is safe and guaranteed to work by the C++ standard. Here's what Herb Sutter has to say:

这篇关于将read()直接使用到C ++ std:vector中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 22:29