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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…