C++: Is not deleting an object /always/ a memory leak?
class MyClass
{
// empty class with no base class
};
int main()
{
MyClass* myClass = new MyClass();
re开发者_如何学Goturn 0;
}
Is this a memory leak?
Yes. Even though your class is empty, you still leak memory. There are a few reasons for this:
- Allocations are never zero-length. Your OS doesn't hand back a buffer of zero bytes. There is a minimum allocation size, and this is the size you'll get if you allocate a zero-byte structure. (On my machine, it's 16 bytes.)
- Even if zero-length allocations existed, objects are systematically at least 1 byte large (where the size of a byte is the same as the size of a
char
). - Even if you did get a zero-length allocation, your OS has to keep track of this allocation. To do so, it uses a few more bytes to map the address to its allocation details. This has a constant size memory overhead that you get every time you allocate memory.
So, your code leaks at least one byte of memory, plus the allocation details, even if your struct is empty.
You have a memory leak any time that:
- you dynamically allocate an object, then
- you lose all pointers and references to that dynamically allocated object
at this point, you are incapable of destroying the dynamically allocated object and thus the object is leaked.
In your example program, you dynamically allocate a MyClass
object and set myClass
to point to it. myClass
is the only pointer to the dynamically allocated object. You then return from the function and lose the pointer; at this point, the dynamically allocated MyClass
object is leaked.
Whether or not this matters depends on what the object is, what the program is, and when the leak occurs. If the object doesn't need to do any cleanup when it is destroyed (e.g., if its destructor is trivial), then failing to destroy it before the program terminates is usually bad style but is not particularly bad, relative to other sorts of leaks.
Note that everything is guaranteed to be at least the size of a C++ byte, which is always the same size as a char
. (Your mileage may vary on exotic systems, but this is generally eight bits. Check with CHAR_BIT
.) So, yes, it will take up memory (albeit very little) and that memory will be leaked.
Therefore, not deleting an object will, indeed, always leak memory.
精彩评论