限制C++变量的范围
Limit a C++ Variable's Scope
我有一个C++程序,其形式如下:
int main(){
int answer;
...
MEMORY_CONSUMING_DATA_ARRAY temp;
a few operations on the above;
answer=result of these operations;
... //More code
}
也就是说,我有一小块代码,它似乎不能保证自己的功能,但它使用了大量的内存。
我想在有限的范围内引入消耗内存的变量(类)以产生结果,然后将其销毁。帮助程序函数可以轻松做到这一点,但在我工作的场景中似乎有点矫枉过正。
关于如何实现这一目标的任何想法?
谢谢!
如果你需要销毁:
int main() {
int answer;
...
{ // << added braces
MEMORY_CONSUMING_DATA_ARRAY temp;
a few operations on the above;
answer=result of these operations;
}
... //More code
}
因此,这将适用于由动态分配支持的集合/对象,例如std::vector
。
但是对于大型堆栈分配...你任由编译器摆布。编译器可能会决定最好在函数返回后清理堆栈,或者可能会在函数中以增量方式执行清理。当我说清理时,我指的是你的函数所需的堆栈分配 - 而不是破坏。
要对此进行扩展:
销毁动态分配:
int main() {
int answer;
...
{ // << added braces
std::vector<char> temp(BigNumber);
a few operations on the above;
answer=result of these operations;
// temp's destructor is called, and the allocation
// required for its elements returned
}
... //More code
}
与堆栈分配相比:
int main() {
int answer;
...
{
char temp[BigNumber];
a few operations on the above;
answer=result of these operations;
}
// whether the region used by `temp` is reused
// before the function returns is not specified
// by the language. it may or may not, depending
// on the compiler, targeted architecture or
// optimization level.
... //More code
}
Justin 的回答很好,但如果你一次又一次地执行此操作,那么你可能需要重用这个内存。
编辑
如前所述,静态将使内存不分配在堆栈上,这可能会使您受益,如果您每次都需要将内存清零,这也是可选的,如果您每次都要复制相同的数量并且不会读取超过这一点,那么您可以保存对零内存或其他初始化调用的调用。
int main(){
int answer;
...
{
static MEMORY_CONSUMING_DATA_ARRAY temp; // make this static or a member perhaps
temp = 0; // initialise it every time to clear the memory or zeromemory or other op
a few operations on the above;
answer=result of these operations;
}
... //More code
}
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 如果非动态变量被指针引用,何时超出范围?
- 为什么我的变量存在于其范围之外
- 变量超出范围后如何保留向量值?
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 在 c++ 中确定堆栈上的变量范围
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 如何从未知视图中声明范围::v3::View 变量
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 是否未定义将对函数范围变量的引用作为值返回
- 无法从另一个函数访问文件范围变量的内容
- 如何访问C 中的功能范围变量
- C++ 程序和范围变量
- 性能对象属性与范围变量
- 存储lambda函数,该函数将范围变量捕获为类成员以供重用
- 何时分配块范围变量
- 在 c++ 中声明一个全局范围变量 const