简体   繁体   中英

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().

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?

Is destructor of that class called every time it created again in that for loop?

Yes, the variables have automatic storage so A 's destructor is called each time one of them goes out of scope.

Provided your class is well behaved, memory allocated in A should get dealt with appropriately. 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.

For more on that last point see the rule of three .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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