How is is_standard_layout useful?

后端 未结 1 1251
南方客
南方客 2021-02-13 13:46

From what I understand, standard layout allows three things:

  • Empty base class optimization
  • Backwards compatibility with C with certain pointer casts
1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-13 14:11

    General response

    It is a way of validating assumptions. You wouldn't want to write code that assumes standard layout if that wasn't the case.

    C++11 provides a bunch of utilities like this. They are particularly valuable for writing generic code (templates) where you would otherwise have to trust the client code to not make any mistakes.


    Notes specific to is_standard_layout

    It looks to me like the (pseudo code) definition of is_pod would roughly be...

    // note: applied recursively to all members
    bool is_pod(T) { return is_standard_layout(T) && is_trivial(T); }
    

    So, you need to know is_standard_layout in order to implement is_pod. Given that, we might as well expose is_standard_layout as a tool available to library developers. Also of note: if you have a use-case for is_pod, you might want to consider the possibility that is_standard_layout might actually be a better (more accurate) choice in that case, since POD is essentially a subset of standard layout.

    I get the feeling that they added every conceivable variant of type evaluation, regardless of any obvious value, just in case someone might encounter a need sometime before the next standard comes out. I doubt if piling on these "extra" type properties adds a significant additional burden to compiler developers.

    There is a nice discussion of standard layout here: Why is C++11's POD "standard layout" definition the way it is? There is also a lot of good detail at cppreference.com: Non-static data members

    0 讨论(0)
提交回复
热议问题