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

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

问题描述

如果类声明如下:

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

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

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