c++ - POD 中的 static_assert 会破坏 POD 吗?

标签 c++ types assert static-assert

我只是想知道...假设我有一个 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 (标量类型,具有普通默认构造函数的普通可复制类,或此类类型/类的数组)
  • standard layout (没有虚函数,没有虚基类等)

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

static_assert s 在那里是为了在编译时验证某些东西,并且不会改变对象布局或对象的构造、复制等过程中的琐碎性(或缺乏琐碎性)。因此,向类型(结构/类)添加任意数量的静态断言不应改变它的 POD 特性。

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

这就是标准关于 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.

关于c++ - POD 中的 static_assert 会破坏 POD 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31804618/

相关文章:

java - 在Java中是空类型

java - Assert.notThrown 可以在抛出异常时指定一条消息

c# - 断言方法错误

c++ - 在哪里学习硬件编程?

c++ - 为什么我的程序不读消除左递归文法规则? C++

c++ - 重新启动流式 OpenAL 源代码?

c++ - 输入 int 和 str 并将它们存储到两个单独的列表中

c++ - 你能在 bool 变量中存储/转换 int 值吗?

使用类型类进行 Haskell 函数参数类型推断

c# - Assert.True 未通过测试