How to delay Destructor call in a loop

Viewed 46
// Online C++ compiler to run C++ program online
#include <iostream>
#include <iterator>
#include <set>
int index;
int member[5] = {0,1,2,3,4};
class Animal{
    public:
    Animal(int val){
        member[val]=-1;
    }
    
    ~Animal(){
        member[index]=index;
    }
    
};

int main() {
    // Write C++ code here
    for(int i=0;i<5;i++){
        std::cout<<member[i]<<" ";
    }
    std::cout<<std::endl;
    
    for(int i=0;i<5;i++){
        index=i;
        Animal a(i);
    }
    
    for(int i=0;i<5;i++){
        std::cout<<member[i]<<" ";
    }
    return 0;
}

In following code the output is:

0 1 2 3 4

0 1 2 3 4

But I am interested in the following output:

0 1 2 3 4

-1 -1 -1 -1 -1

So every time we perform Animal a(i); its constructor gets called and member[val]=-1 but immediately after its iteration the destructor gets called which makes the value back to val. member[index]=index.

How can we delay the call to destructor in this case?

I want the member[5]={-1,-1,-1,-,1,-1} after the for loop ends

and member[5]={0,1,2,3,4} restored to original value only when main() exists.

1 Answers

While it's an ugly hack, how about using a vector that gets destructed after the code you're interested in?

Perhaps something like:

{
    std::vector<Animal> animals;

    for(int i = 0; i < 5; ++i){
        std::cout << member[i] << ' ';
    }
    std::cout << '\n';

    for(int i = 0; i < 5; ++i){
        animals.emplace_back(i);
    }

    for(int i = 0; i < 5; ++i){
        std::cout << member[i] << ' ';
    }
    std::cout << '\n';

    // Here the vector object life-time ends
    // All Animal object will be destructed
}

As noted, this solution will use the last value of index when the Animal object are being destructed, and since it's never used by the above code it will stay at its (implicitly) initialized value of 0.

You need to store the "index" passed to the constructor in an actual member variable, and use it in the destructor:

class Animal
{
public:
    Animal(int index)
        : my_index{ index }
    {
    }

    ~Animal()
    {
        member[my_index] = my_index;
    }

private:
    int my_index;
};

After this you can remove the global index variable, as it's no longer used or needed.

Related