简体   繁体   中英

Memory use for custom struct functions in vector of structs

I have a struct, for example this one:

struct TMyStruct {
    int v1;
    std::string abc;

    TMyStruct() { Init(); }

    void Init() {
        v1 = 1;
        abc = "text";
        }
    }

std::vector<TMyStruct> ms;
ms.push_back(TMyStruct());
// ... etc.

It works nicely.

My concern is - does the above structure uses more memory because of the additional functions for initialization in this case (but could be anything else) when allocated in a vector? Or should I use the struct without any additional functions for example:

struct TMyStruct {
    int v1;
    std::string abc;
    }

std::vector<TMyStruct> ms;
ms.push_back(TMyStruct());
ms.back().v1 = 1;
ms.back().abc = "text";
// etc...

Member functions (excluding virtual functions that require a pointer to the table of pointers to virtual functions) do not influence on the size of a class.

Member functions will not cost any additional memory, unless at least one of them is declared virtual, in which case you will pay for an additional pointer to the virtual memory table, and some constant amount of memory for the table itself.

In case you would assign a longer string to abc , your constructor will be more costly in terms of memory usage compared to the same struct without a custom constructor.

Finally, your constructor will be a bit more costly in terms of runtime overhead compared to the version without a constructor, but it will not be noticeable in practice.

Member functions does not affect size of an instance of a class. In your case specially, cause your extra function is not virtual, and you have no inheritance involved. Small size penalty would come if you would introduce inheritance and virtual functions, cause any instance of class in such case would contain an extra pointer to vTable.

So, long story short, your structure does not use more memory cause you use extra init function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM