c++ - 对象成员的位置

标签 c++

<分区>

Possible Duplicate:
Are data members allocated in the same memory space as their objects in C++?

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

void main() {
  MyClass class;
}

它将在堆栈上自动创建。

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

class MySecondClass {
  private:
    MyClass class;
}

成员会在栈上创建吗?如果是这样,如果通过 new 创建 MySecondClass 会怎样?这个成员还会在堆栈上吗?

最佳答案

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?

没有。它将与对象的其余部分一起存储,“在堆上”或实现自由存储的任何位置,或者动态分配对象的任何位置(可能是某个内存池或其他东西)。

这里值得注意的是术语“堆栈”和“堆”通常被误用。您真正要问的是以下内容:

成员(member)有自动存储期限吗?有。

即使封装对象具有动态存储持续时间,它也会这样做吗?不会——封装对象的动态是,在一个意义,“继承”。

[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).

在这两种情况下,内存中的实际位置分别是堆栈和空闲存储(“堆”),这并不重要。

而且,顺便说一下,main 必须int 返回类型。

关于c++ - 对象成员的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13743357/

相关文章:

C++:访问祖 parent 方法

c++ 传递字符串文字而不是 const std::string&?

c++ - cv::Mat 到 QImage 并返回

c++ - 在 vc++ 中使用模板限制类型

c++ - 从多个 map<key,value> 中搜索的最佳方式是什么?

c++ - 使用 Visual Studio 2008 进行跨平台编译

c++ - 符号未出现在目标文件中

c++ - stat() 在 C++ 中找不到文件

c++ - 为什么我们需要将函数标记为constexpr?

c++ - 在多线程C++应用程序中检测阻塞调用