类成员在堆/堆栈上分配? [英] Class members allocation on heap/stack?

查看:62
本文介绍了类成员在堆/堆栈上分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果类声明如下:

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

可以这样做:

class MyClass
{
  char MyMember[250];
};

如何在堆上分配类,就像我执行MyClass * Mine = new MyClass(); 在第二个示例中,分配的内存是否还分配了250个字节以及类实例化?并且该成员在MyClass对象的整个生命期内都有效吗? 对于第一个示例,在堆上分配类成员是否可行?

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?

推荐答案

是的,是的,是的.

尽管,您的第一个示例中存在一些错误:这是因为它的数据成员之一是具有堆分配数据的指针,因此它还应声明一个复制构造函数和赋值运算符,用于例如...

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

这篇关于类成员在堆/堆栈上分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆