Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

c++ - where are member-vars of a class on the heap stored?

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

will this make any difference

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Non-static data members are stored inside the object (class instance) they're part of.

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.

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.

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;
    // ...
};

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.


A note on terminology:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...