Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class members allocation on heap/stack?

If a class is declared as follows:

class MyClass
{
  char * MyMember;
  MyClass()
  {
    MyMember = new char[250];
  }
  ~MyClass()
  {
    delete[] MyMember;
  }
};

And it could be done like this:

class MyClass
{
  char MyMember[250];
};

How does a class gets allocated on heap, like if i do MyClass * Mine = new MyClass(); Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation? And will the member be valid for the whole lifetime of MyClass object? As for the first example, is it practical to allocate class members on heap?

like image 937
SimpleButPerfect Avatar asked May 12 '10 15:05

SimpleButPerfect


People also ask

Are classes stored in heap or stack?

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space, and the references to these objects are stored in stack memory.

Are member variables on the heap?

Member variables are members of the class itself. They are neither on the heap nor on the stack, or rather, they are where ever the class itself is.

What gets allocated on the heap?

Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create an object, it's always created in the Heap space.

Are allocations faster on heap or stack?

The stack is faster because the access pattern makes it trivial to allocate and deallocate memory from it (a pointer/integer is simply incremented or decremented), while the heap has much more complex bookkeeping involved in an allocation or free.


2 Answers

Yes, yes, and yes.

Your first example has a bit of a bug in it, though: which is that because it one of its data members is a pointer with heap-allocated data, then it should also declare a copy-constructor and assignment operator, for example like ...

MyClass(const MyClass& rhs) 
{
  MyMember = new char[250]; 
  memcpy(MyMember, rhs.MyMember, 250);
}
like image 123
ChrisW Avatar answered Sep 21 '22 07:09

ChrisW


Early note: use std::string instead of a heap allocated char[].

Does the allocated memory also allocates the 250 bytes in the second example along with the class instantiation?

It will be heaped allocated in the constructor, the same way as in a stack allocated MyClass. It depends what you mean by "along with", it won't necessarily be allocated together.

And will the member be valid for the whole lifetime of MyClass object?

Yes.

As for the first example, is it practical to allocate class members on heap?

Yes, in certain cases. Sometimes you want to minimize the includes from the header file, and sometimes you'll be using a factory function to create the member. Usually though, I just go with a simple non-pointer member.

like image 21
Stephen Avatar answered Sep 18 '22 07:09

Stephen