加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在范围内构造向量而不复制

发布时间:2020-12-16 07:16:10 所属栏目:百科 来源:网络整理
导读:我有一个包含大量字节的类,这些字节是网络数据包.该类实现一个队列并提供(以及其他)front()函数,该函数返回构成队列中最旧数据包的字节的const向量. class Buffer{ unsigned char data[65536]; unsigned int offset; unsigned int length; [...]//other fiel
我有一个包含大量字节的类,这些字节是网络数据包.该类实现一个队列并提供(以及其他)front()函数,该函数返回构成队列中最旧数据包的字节的const向量.

class Buffer{
  unsigned char data[65536];
  unsigned int offset;
  unsigned int length;
  [...]//other fields for maintaining write ptr etc.

public:
  const std::vector<unsigned char> front(){
    return std::vector<unsigned char>(data + offset,data + offset + length);
  }

  //other methods for accessing the queue like
  //pop(),push(),clean() and so forth...
  [...]
}

上述front()函数实现的性能受到当前数据包占用范围内不必要的复制字节的影响.由于向量是常量,因此不需要复制数据.我想要的是在已经存储在缓冲区中的数据上创建一个向量.当然,向量的析构函数不应该释放内存.

解决方法

您有一些选择:

>而不是返回一个向量,只需返回一个const char *:

const char* front() {
    return data;
}

>考虑使用标准容器,例如字符串数据作为缓冲区成员.这将允许您:

const string& front() {
    return data;
}

>最好的选择是,如果您有C 17或访问experimental::string_view,您可以这样做:

const string_view front() {
    return string_view(data);
}

只是一个约定评论,前面会有一个期望,它将像其他标准容器一样,其中:

Returns a reference to the first element in the container.
Calling front on an empty container is undefined.

[source]

C标准委员会还讨论了将正面应用于裸露的固定尺寸阵列:front and back Proposal for iterators Library

因为这种方法更接近数据,其中:

Returns a pointer to the block of memory containing the elements of the container.

[source]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读