Question

Possible Duplicate:
C++: What is the size of an object of an empty class?

if the class does not have any data member and just has the mehod, it still has a chance of memory leak. First the class method is reference to class object and object still needs memory to store the address when allocating. Am I correct?

class Empty
{
  doA()
  {
  }
};
Was it helpful?

Solution

if the class does not have any data member and just has the mehod, it still has a chance of memory leak.

Yes, you can still leak memory on that type. You can leak on any type, even a type with no members. sizeof(EmptyClass) will never equal 0. See: http://www.stroustrup.com/#sizeof-empty

From the spec:

The size of a most derived class shall be greater than zero.

OTHER TIPS

Well, even empty classes are required to have sizeof be larger than 0 and so the class will still take up space. The reason is because unique objects should have unique addresses. The fact that it has member functions (methods) or not is irrelevant.

So this will leak:

new Empty; // leaking at least 1 byte

Every class instance is required by the standard to have non-zero size, even empty classes. See this answer for the reason why.

The following is not required by the standard, but applies to every compiler I've used (Visual C++, GCC, Clang):

Instances don't store addresses to member functions. The compiler already knows the address of every member function at compile/link time. So, a class with 100 members functions and only one float data member will only take up sizeof(float) bytes of space.

If a class has virtual functions, every instance of that class will need storage for a virtual function table pointer.

Any object in the memory requires "space". Even an empty class like that will have Constructor and CopyConstructor automatically thrown into it. All of that will require memory. And forgetting to delete that memory will cause memory leak of exactly sizeof(Empty) bytes. It does not matter if its 1byte or several.

It will depend on how you allocate your object, and at most cases (or all of them), even if the class is empty, if you allocate it using for example new or malloc and similar methods, you'll have a memory leak if you lose the pointer to it. But it also depends on the implementation.

That's because new or malloc both have ways of storing information for the allocated object near the object's memory space.

If you don't use the declared class at all, the compiler might optimize it away, thus you would not have any memory leak because you have never allocated memory for it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top