简体   繁体   English

C ++删除函数中的局部变量

[英]C++ deleting local variables in function

I have function that works on class A. Class A allocates some memory in constructor and frees it in destructor A::~A(). 我有在类A上工作的函数。类A在构造函数中分配一些内存,并在析构函数A ::〜A()中释放它。

Now what if. 现在,如果。

A someFunc()
{
//This is just to illustrate that it is possible for that variable to be overwritten few times before returning.

A locA;

for(some condition)
{
    //Something something
    A forA(i);
    //Something.
    if(end) locA = forAj;
}

return locA;
}

Is this good? 这个好吗? Is destructor of that class called every time it created again in that for loop? 每次在该for循环中再次创建该类的析构函数时,都会对其进行调用吗?

Is destructor of that class called every time it created again in that for loop? 每次在该for循环中再次创建该类的析构函数时,都会对其进行调用吗?

Yes, the variables have automatic storage so A 's destructor is called each time one of them goes out of scope. 是的,变量具有自动存储功能,因此每当其中一个变量超出范围时,都会调用A的析构函数。

Provided your class is well behaved, memory allocated in A should get dealt with appropriately. 只要您的班级表现良好,就应该适当处理A分配的内存。 Note that this means that in your case, A should also have a suitable copy constructor and a copy assignment operator in order to be well behaved. 请注意,这意味着在您的情况下, A还应具有合适的副本构造函数和副本赋值运算符,以便表现良好。

For more on that last point see the rule of three . 有关最后一点的更多信息,请参见三法则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM