gpt4 book ai didi

c++ - `std::vector` 会做任何我没有要求的事情吗

转载 作者:行者123 更新时间:2023-11-30 00:51:42 25 4
gpt4 key购买 nike

在 C++ 中,如果我初始化一个 std::vector v(100); 并且从不尝试 resize()reserve() 它,capacity() 是否保证始终保持不变?我想确保没有内存 alloc/freeing/realloc/etc 出于性能原因而进行。 (是的,这会影响性能;我的函数一直被调用,它们必须快速返回)。

恢复一切:

std::vector<float> v;
// somehow, `v' is initialized to have 100 elements
void f() { // this function must return _very_ quickly
/* do some processing, without ever calling v.resize() or v.reserve(), but
accesing v.size() and v[i] all the time */
/* it is guaranteed that no system calls (such as memory management)
will take place here? */
} // no objects on the stack whose destroyers might try to `delete' anything.

最佳答案

来自 C++11 23.3.6.3“vector 容量”中关于 vector::reserve() 的评论:

It is guaranteed that no reallocation takes place during insertions that happen after a call to reserve() until the time when an insertion would make the size of the vector greater than the value of capacity().

关于c++ - `std::vector` 会做任何我没有要求的事情吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20877837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com