静态const std :: vector< char>没有堆初始化? [英] static const std::vector<char> initialization without heap?

查看:78
本文介绍了静态const std :: vector< char>没有堆初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我想拥有一个无符号字符的std :: vector.它使用初始化列表(这是C ++ 11)进行了初始化,并且永远不会更改.我想避免任何堆分配,即使在启动时,也要让整个向量像const字符串一样存在于数据段中.那可能吗?IE:静态const vector< char>v {0x1,0x2,0x3,0x0,0x5};(这是一个有点学术性的问题;我知道为此使用C数组并不难.)

Let's say I'd like to have a std::vector of unsigned chars. It's initialized with an initializer-list (this is C++11) and will never change. I'd like to avoid any heap allocation, even at startup time, and have the whole vector live in the data segment like const strings. Is that possible? I.e: static const vector<char> v{0x1, 0x2, 0x3, 0x0, 0x5}; (This is a somewhat academic question; I know it's not that hard to just use C arrays for this.)

推荐答案

为什么不只使用

Why not just use a std::array for this?

static const std::array<char, 5> v{0x1, 0x2, 0x3, 0x0, 0x5};

这避免了任何动态分配,因为 std :: array 使用的内部数组很可能声明为 T arr [N] ,其中N是您传递的大小在模板中(此处5).

This avoids any dynamic allocation, since std::array uses an internal array that is most likely declared as T arr[N] where N is the size you passed in the template (Here 5).

在这里时,您甚至可能希望将变量 正如@MSalters指出的那样,constexpr 为编译器提供了更多的机会来消除 v 的存储."

While you're here, you might even want to make the variable constexpr, which, as @MSalters points out, "gives the compiler even more opportunity to eliminate the storage for v."

这篇关于静态const std :: vector&lt; char&gt;没有堆初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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