Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...