The following is the best “minimum working example” I can construct for now. I would like to understand if the following code leaks memory.
// Class CTest
class CTest {
vector<int> Elements;
CTest (vector<int>&);
~CTest ();
};
CTest::CTest (vector<int>& Elements_) {
this->Elements = Elements_;
}
CTest::~CTest () {
}
// main
int main (int argc, char *argv[]) {
vector<CTest> V;
for (auto i = 0; i < 10; i++) {
vector<int> U;
for (auto j = i; j < i + 5; j++) U.push_back (j);
V.push_back (*(new CTest (U)));
}
// Do whatever
return 0;
}
Am I correct in thinking that since there isn’t a corresponding invocation of delete for each invocation of new, this programme does indeed leak memory?
Yes, you are correct. Moreover, your code is of the type “trying very hard to get it wrong”, since
vectoris already a dynamic container and you have no reason to perform another dynamic allocation for your element (just to have it copied).There are many more ways to screw up. None of those are a particular design problem of C++, but there’s simply a limit to what the language can stop you from doing. Some more examples:
Fortunately, it is almost always fairly obvious that you’re doing something you’re not supposed to.