元素存储在std::vector内的实际位置是在堆还是栈中?

huangapple go评论70阅读模式
英文:

Is the actual location where the elements inside the std::vector<std::string> are stored in the heap or stack?

问题

关于 vector<char>vector<int>char 元素和 int 元素都存储在堆栈中,但是对于 vector<string> 呢?

如果我想存储一个包含许多字符串的大型 vector<string>,我应该使用 new vector<string> 将我的向量存储在堆中吗?

英文:

As for vector&lt;char&gt; and vector&lt;int&gt;, the char elements and the int elements are both stored in the stack,but what about a vector&lt;string&gt;?

If I want to store a huge vector&lt;string&gt; with many strings, should I use new vector&lt;string&gt; to store my vector in the heap?

答案1

得分: 3

你在过度思考这个。

只需使用 vector<string>。它会为你管理分配,并且 sizeof(std::vector<...>) 是固定且合理的。

即使在使用 std::array 的情况下,它更像C数组,包括大小在内,如果需要,std::string 也会使用动态分配。

几乎不需要使用 new std::vector<...>

英文:

You're over-thinking this.

Just use vector&lt;string&gt;. It manages the allocations for you, and sizeof(std::vector&lt;...&gt;) is fixed and reasonable.

Even then, if you were using std::array which acts a lot more like a C array, size and all, std::string will use dynamic allocation if necessary.

Using new std::vector&lt;...&gt; is hardly ever necessary.

huangapple
  • 本文由 发表于 2023年7月14日 09:46:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76684230.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定