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);
}
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
vectorinstance here is inside your structure, butvectoritself manages its own dynamic storage for the items you push into it. So, theabcinstance is dynamically allocated in the usual free store with itsvectormember inside it, and42is in a separate dynamic allocation managed by thevectorinstance.For example, say vector is implemented like this:
then
capacity_andused_are both part of your vector object. Thedata_pointer is part of the object as well, but the memory managed by the vector (and pointed at bydata_) is not.A note on terminology:
::operator new. There could be anything in there, it’s another implementation detail.