简体   繁体   中英

Memory leak (sort of) with a static std::vector

I have a static std::vector in a class. When I use Microsoft's memory leak detection tools:

_CrtMemState state;
_CrtMemCheckpoint( & state);
_CrtMemDumpAllObjectsSince( & state );

it reports a leak after I insert stuff into the vector. This makes sense to me because new space is allocated when something is inserted into the vector. This space isn't deallocated until the program terminates (since the vector is static). Is this right?

In the destructor of the class that contains the vector, I'm deleting the object that I put into the vector. However, the memory that's allocated when the insertion happened is still hanging around. Is there anyway to delete this space?

You can swap the vector with an empty one - this will release the memory.

See also Q: Shrinking a vector

To add to what James wrote. He means to do this:

std::vector<T>().swap(v);

where 'v' is the vector whose memory you want to release.

That is just a quirk of Visual Studio. The vector destructor does release the memory, but the memory checking module doesn't always spot it, so it complains. It is a bit of a pain, but nothing to worry about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM