How is is_standard_layout useful?

感情迁移 提交于 2019-12-05 14:21:36

问题


From what I understand, standard layout allows three things:

  • Empty base class optimization
  • Backwards compatibility with C with certain pointer casts
  • Use of offsetof

Now, included in the library is the is_standard_layout predicate metafunction, but I can't see much use for it in generic code as those C features I listed above seem extremely rare to need checking in generic code. The only thing I can think of is using it inside static_assert, but that is only to make code more robust and isn't required.

How is is_standard_layout useful? Are there any things which would be impossible without it, thus requiring it in the standard library?


回答1:


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



来源:https://stackoverflow.com/questions/15994237/how-is-is-standard-layout-useful

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!