Question about case with return, object destructor, and dynamic memory

Hello,

I have a class that contains a vector member, which stores a lot of data. I want the class to automatically clean up the memory when an object of this class goes out of scope, like so:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Data
{
public:     
     Data();
     ~Data();
     std::vector<double> x;
     
}

Data::~Data()
{
     x.clear(); //clears x when Data is destroyed
}

int main()
{
     Data data;
     
     return;  //Vector should be cleared here
}


The problem is that I want to set all of data's members via the copy assignment operator and a return call from an outside function. The function looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Data Create_Data()
{
     Data data;
     data.x[1]=1;
     data.x[2]=2;
     //etc.
    
     return data;
}

int main()
{
     Data data;
     data = Create_Data(); //x.clear() should be called here
     std::cout << data.x[1]; //Why doesn't this crash?
     return;
}


I just tested this and I'm confused about the result. What happened is that data in int main() still contained the entire x vector. My expectation was that if I tried doing something liket he cout statement above, the program would crash because the destructor is called when data goes out of scope at the end of Create_Data.

Could someone explain this to me? I'm really curious.

Thanks
Last edited on
1) clearing vector in destructor is useless: it would be destroyed anyway.
2) Data returned by Create_Data is copy of Data used by it internally. When original is destroyed, it cannot change copy which made prior to destruction. Each Data object has own copy of data which has no relation to each other.
Topic archived. No new replies allowed.