0

我有以下课程:

class CObj {
private:
    MyOtherClass _member;
};

以及创建 CObj 类实例的以下代码:

CObj* obj = new Cobj;

obj 在堆上分配,但是: CObj::_member 是否也在堆上分配?还是在堆栈上?

4

3 回答 3

4

obj是“在堆栈上”分配的指针;对象obj指向的是“在堆上”,并且作为obj->_member这样一个对象的成员(=一部分),它也在堆上。

通常,作为父对象一部分的成员被分配到存储其父对象的任何位置。

于 2013-10-22T11:49:55.270 回答
3

_member has automatic storage duration - it is allocated where it's owning object is allocated. So, if you create an instance of CObj with dynamic storage duration, like in your example, it will also be allocated in dynamic storage (the heap). If you create an object with automatic storage duration, it will be on the stack.

The problem with such questions is that C++ does not have any concept of stack and heap - it's just storage durations.

于 2013-10-22T11:55:13.307 回答
0

When you call new OS allocate as much memory as size of class on heap and call class contructor.

From this you can see that since MyOtherClass is in CObj and CObj holds MyOtherClass , MyOtherClass is also on heap in same space as CObj .

于 2013-10-22T11:54:28.350 回答