Reputation: 1349
I'm using numerous vectors in a program and I want to avoid memory leaks. Here is an example of a vector containing classes I have created myself.
vector<MyClass> objects;
objects = vector<MyClass>(10);
As you can see, I haven't used the "new" operator and the vector is not of a pointer type. Will I still encounter memory leaks without deleting the vector in some way? If so, how can I delete the vector and deallocate the memory?
Upvotes: 0
Views: 134
Reputation: 77324
A memory leak is defined as memory that exists, but you don't have access to anymore because you lost the pointer. Do this in a loop and you will be out of available memory real quick.
If you don't use new
to allocate memory dynamically, you cannot have a memory leak.
Lets assume you add instances to this vector in a loop. This consumes a lot of memory. But it's not a leak, because you know exactly where your memory went. And you can still release it if no longer needed.
Upvotes: 1
Reputation: 12907
No, you won't encounter directly a memory leaks related to the vector this way. Indeed, objects
is a variable with automatic storage duration. What this means is that the variable you created will live in the scope you created it. If you've created it in a function, and if/for/while/etc scope or even a raw block scope, it will be cleaned up at the end of this same scope, without the need for any actions from your part.
Then, nothing is preventing your class itself from leaking, e.g. if you have ownership of some memory and don't release it as an instance of your class go away.
Upvotes: 1