C++循环堆栈分配

1 c++ stack memory-management

在做一个课程的分配和学习C++的同时,我正在阅读何时使用堆栈分配和动态分配.我知道在很多情况下使用堆栈分配更容易也更好.但是有一个简单的情况我被困惑了.

让我们说你有一个for循环:

for(int i = 0; i < 10; i++)
{
   MyObject obj(file);
   obj.doSomething();
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是,如果Object包含状态,它会保持状态(保持相同的对象),同时迭代从1到10的迭代.也许来自Java/C#背景让我走错了路.但我只看到两种解决方法:

  1. 使用动态内存.
  2. 不给文件构造函数,而是给方法,doSomething(file)但如果你有多个方法操作文件对象,这不是很好doSomethingElse(file).

那么你们在这种情况下做了什么,或者你们从来没有让自己陷入这种境地?

更新: 原来我被误解了,它正在按预期工作.检查下面的芒果!感谢大家

Jam*_*mes 5

在您发布的代码中,obj在迭代之间不保持任何状态.

for(int i = 0; i < 10; i++) 
{    
  MyObject obj(file); //obj enters scope, constructor is called with 'file'
  obj.doSomething(); 
}  //obj loses scope, destructor is called
Run Code Online (Sandbox Code Playgroud)

在该示例中,obj每次都是不同的对象.它可能使用与前一个对象相同的"堆栈"内存位置,但是在迭代之间调用类析构函数和构造函数.

如果您希望仅将对象构造一次并重复使用,请在循环之前构造.

function(file)
{
    MyObject obj(file); //obj enters scope, constructor is called with 'file'

    for(int i = 0; i < 10; i++) 
    {    
      obj.doSomething(); //Same object used every iteration
    }  

}  //obj loses scope, destructor is called
Run Code Online (Sandbox Code Playgroud)