对象的成员的位置 [英] Location of members of an object

查看:110
本文介绍了对象的成员的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如果我声明一个这样的对象:

If I declare an object like this:

void main() {
  MyClass class;
}

它会自动在堆栈上创建。

it will be created automatically on the stack.

如果我这样做会发生什么:

What happens if I do this:

class MySecondClass {
  private:
    MyClass class;
}

成员是否会在堆栈上创建?如果是这样,如果 MySecondClass 是通过 new 创建的,会发生什么?

Will the member be created on the stack? If so, what happens if MySecondClass is created via new? Will this member still be on the stack?

推荐答案


成员是否会在堆栈上创建?

Will the member be created on the stack?

是的。


如果 MySecondClass 是通过 new 创建的,会发生什么?此成员是否仍在堆叠中?

If so, what happens if MySecondClass is created via new? Will this member still be on the stack?

否。它将与对象的其余部分,在堆上或实现自由存储的任何位置一起存储,或者在对象被动态分配(可能是一些内存池或其他内容)的任何地方存储。

No. It will be stored along with the rest of the object, "on the heap" or wherever your free store is implemented, or wherever the object gets dynamically allocated (which could be some memory pool or something else).

这里值得注意的是,术语stack和heap通常是错误使用。 要求的是以下内容:

It's worth noting here that the terms "stack" and "heap" are generally mis-used. What you're really asking is the following:

会员是否拥有自动存储持续时间是的。

Does the member have automatic storage duration? Yes.

即使封装对象具有动态存储持续时间< —封装对象的动态在某种意义上是继承的。

Will it do so even when the encapsulating object has dynamic storage duration? No — the dynamicness of the encapsulating object is, in a sense, "inherited".


[C ++ 11:3.7.5]:成员子对象,基类子对象和数组元素的存储持续时间是它们完整对象(1.8)的存储持续时间。

[C++11: 3.7.5]: The storage duration of member subobjects, base class subobjects and array elements is that of their complete object (1.8).

在任何一种情况下,内存中的实际位置分别是栈和自由存储(heap),这并不重要。

The practical location in memory in either case will be the stack and the free store ("heap") respectively, and that doesn't really matter.

顺便说一句, main 必须 int 返回类型。

And, by the way, main must have int return type.

这篇关于对象的成员的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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