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

前端 未结 3 674
庸人自扰
庸人自扰 2020-12-07 05:26

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

3条回答
  •  心在旅途
    2020-12-07 06:07

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

提交回复
热议问题