How much functionality is “acceptable” for a C++ struct?

后端 未结 19 2319
礼貌的吻别
礼貌的吻别 2021-02-07 09:31

My first post so please go easy on me!

I know that there\'s no real difference between structs and classes in C++, but a lot of people including me use a struct or class

19条回答
  •  再見小時候
    2021-02-07 09:52

    My simple rule of thumb for structs and classes:

    if (data_requires_strict_alignment == TRUE) {
      use(struct);
    } else {
      use(class);
    }
    

    That is, if the data you are representing corresponds to some data object that has strict member order and alignment requirements (for example, a data structure exchanged with hardware on the driver level), use a struct. For all other cases, use a class. Classes have so many features and capabilities that structs do not, and in my experiences it is beneficial to use classes whenever possible, even if you are not using any of those additional features at the moment (if nothing else, a data-only class is like a struct with a safer default access level). Reserve structs for those cases when you need the unique properties of a struct; namely, the ability to specify structure members in a precise order and with precise alignment/padding (typically with low-level communication, e.g. drivers) such that you can cast it to a byte array, use memcpy() on it, etc. If you follow this model, then a class would not be used as a member of a structure (since a class definition does not specify alignment or a predictable value for sizeof(class)). Likewise, if you are thinking about constructors or operators, use a class.

    This rule of thumb also helps make it easier to interface with C code, since structs are used in a manner consistent with C structures.

提交回复
热议问题