Reputation: 1976
I've written some simple interface and I want to create a global vector holding objects of a class that implements the interface. So I did the following:
vector<SomeInterface*> ary;
I commented out the whole code apart from: void main() and vector ary; and now using _CrtDumpMemoryLeaks(); in Visual Studio 2010 I get 1 block leaked.
How to fix it?
Regards.
Upvotes: 0
Views: 1035
Reputation: 28178
The vector
isn't the cause of your leaks, I can guarantee that much. You are storing SomeInterface*
s in your vector. I'm assuming you allocate these (new SomeInterface(...)
) and don't delete them anywhere. I suggest you use smart pointers:
std::vector<std::unique_ptr<SomeInterface>> ary;
If you can't do this, you need to delete your allocations after using them...
for(SomeInterface* i : ary)
delete i;
Upvotes: 1
Reputation: 11968
You need to delete the allocated memory. You have two options:
for (auto *p : ary) delete p;
or
vector<std::unique_ptr<SomeInterface>> ary;
The second one is safer, as it will automatically release the memory when you destroy the vector.
Upvotes: 5