Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
409 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...