其中是堆上的类的成员变量存储吗? [英] where are member-vars of a class on the heap stored?

查看:164
本文介绍了其中是堆上的类的成员变量存储吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为一个类在堆上被实例化。所有成员变量然后也分配在堆上,或其他地方。那么在堆上分配成员var是否有好处呢?

As a class is instantiated on the heap. Are all member vars then also allocated on the heap, or somewhere else. Is there then any good in allocating member vars explicit on the heap?

struct abc {
std::vector<int> vec;
}


int main() {
abc* ptr = new abc(); //the "class" is on the heap but where is vec?
ptr->vec.push_back(42); //where will the 42 be stored?
return 0;
}

这会产生任何差异

struct abc {
std::vector<int>* vec_ptr;
abc() { vec_ptr = nev std::vector<int>(); }

int main() {
abc* ptr = new abc();
ptr->vec->push_back(42);
}


推荐答案

非静态数据成员

如果你创建一个具有自动存储持续时间的本地对象,它的成员是
里面它。如果你动态分配一个对象,它们就在里面。
如果你使用一些完全不同的分配方案分配一个对象,它的成员将仍然在它的内部。对象的成员是该对象的部分

If you create an object as a local with automatic storage duration, its members are inside it. If you allocate an object dynamically, they're inside it. If you allocate an object using some entirely different allocation scheme, its members will still be inside it wherever it is. An object's members are part of that object.

请注意,此处向量这里是你的结构,但向量本身管理自己的动态存储为你推入的项目。因此, abc 实例在通常的免费存储中动态分配,其中包含向量成员,而 42 是由向量实例管理的单独动态分配。

Note that here the vector instance here is inside your structure, but vector itself manages its own dynamic storage for the items you push into it. So, the abc instance is dynamically allocated in the usual free store with its vector member inside it, and 42 is in a separate dynamic allocation managed by the vector instance.

例如,假设vector如下实现:

For example, say vector is implemented like this:

template <typename T, typename Allocator = std::allocator<T>>
class vector {
    T *data_ = nullptr;
    size_t capacity_ = 0;
    size_t used_ = 0;
    // ...
};

然后 capacity _ used _ 都是矢量对象的一部分。 data _ 指针也是对象的一部分,但是由向量管理的内存(和 data _ )不是。

then capacity_ and used_ are both part of your vector object. The data_ pointer is part of the object as well, but the memory managed by the vector (and pointed at by data_) is not.


  • 自动储存期间最初在堆叠 。正如Loki指出的(和我在别处提到自己),自动本地存储通常使用调用堆栈实现,但它是一个
  • 动态 - 同一异议适用。
  • >当我说通常的免费商店,我只是意味着任何资源由 :: operator new 管理。其中可能有任何内容,这是另一个实现细节。

  • with automatic storage duration was originally on the stack. As Loki points out (and I mentioned myself elsewhere), automatic local storage is often implemented using the call stack, but it's an implementation detail.
  • dynamically was originally on the heap - the same objection applies.
  • When I say usual free store, I just mean whatever resource is managed by ::operator new. There could be anything in there, it's another implementation detail.

这篇关于其中是堆上的类的成员变量存储吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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