-1

Suppose I have a class:

class Test{
public:
    std::vector<int*> foo;
Test(){
    int * x = new int(5);
    int * y = new int(10);
    foo.push_back(x);
    foo.push_back(y);
}
~Test(){

    for(int i = 0; i < foo.size(); i++){
        delete foo.at(i);
    }
}
void reAssignTest(){
    Test test2;
    *this = test2;
}
};

int main(){
    Test test;
}

I noticed that my for loop in my deconstructor never runs b/c the size of foo is 0 when the deconstructor gets called once my original 'test' instance gets replaced by test2. Thus the int variables in the heap never get destroyed. Is this because the vector has its deconstructor called before my code in my deconstructor runs?

Andrew. Q
  • 1
  • 2

1 Answers1

1

As it turns out, your constructor is also not being called. This is because the line Test test(); in main() declares a method test which takes the input void and returns an object of type Test. This problem will go away as soon as you replace Test test() with Test test{}

Read up on "most vexing parse" or chase down other answers on stackoverflow. See My attempt at value initialization is interpreted as a function declaration, and why doesn't A a(()); solve it?

cplusplusrat
  • 1,435
  • 12
  • 27
  • Sorry I didn't mean to have `Test test();` I've now edited to `Test test;` The issue does still remain with the deconstructor. I'm using Clion and valgrind detects a memory leak. – Andrew. Q Mar 10 '19 at 05:32
  • The problem is in your `reassignTest` method. Lets say you call that method on a instance of `test`. Your `*this=test2` just results in a shallow copy of the member vector `foo`. This means the original raw pointers stored in *this are now leaked. Try commenting that method out and see if CLion still complains. – cplusplusrat Mar 10 '19 at 05:42