POD 中的 static_assert 会破坏 POD 吗?

Will a static_assert in a POD ruin the POD?

我只是想知道...假设我有一个 C++ 中的 POD 结构。如果我将 static_assert 放在那里,它会破坏它是 POD 的事实吗?

我知道我可以轻松地将它放在其他地方,我只是想问问我是否应该这样做...

换句话说(更具体):

#include <iostream>
#include <type_traits>

struct A 
{
    void* ptr;

    static_assert(sizeof(void*) == 8, "Pointer should have size 8; platform unsupported");
};

int main()
{
    // Is it guaranteed that this will evaluate to 'true'?
    std::cout << std::is_pod<A>::value << std::endl;
}

在 C++11 中,一个类型被认为是 POD 如果它是

  • trivial(标量类型,具有普通默认构造函数的普通可复制 class,或此类 type/class 的数组)
  • standard layout(没有虚函数,没有虚基classes等)

基本上没有什么会阻碍复制对象,就好像它们只是由原始字节构成一样。

static_asserts 用于在编译时验证某些内容,并且不会更改对象布局或对象的构造、复制等过程中的琐碎(或缺少)。因此,向一个类型添加任意数量的静态断言 (struct/class) 不应改变它的 POD-ness。

您可以使用 std::is_pod<T>::value 检查编译器是否将类型视为 POD。这在添加 static_asserts 之前和之后都不会改变。

这就是标准关于 static_assert 的全部内容。来自 [dcl.dcl]:

In a static_assert-declaration the constant-expression shall be a constant expression that can be contextually converted to bool. If the value of the expression when so converted is true, the declaration has no effect. Otherwise, the program is ill-formed, and the resulting diagnostic message (1.4) shall include the text of the string-literal, except that characters not in the basic source character set (2.3) are not required to appear in the diagnostic message.