相关疑难解决方法(0)

Constexpr指针值

我试图声明一个constexpr指针初始化为一些常量整数值,但clang正在挫败我所有的尝试:

尝试1:

constexpr int* x = reinterpret_cast<int*>(0xFF);

test.cpp:1:20: note: reinterpret_cast is not allowed in a constant expression
Run Code Online (Sandbox Code Playgroud)

尝试2:

constexpr int* x = (int*)0xFF;

test.cpp:1:20: note: cast which performs the conversions of a reinterpret_cast is not allowed in a constant expression
Run Code Online (Sandbox Code Playgroud)

尝试3:

constexpr int* x = (int*)0 + 0xFF;

test.cpp:1:28: note: cannot perform pointer arithmetic on null pointer
Run Code Online (Sandbox Code Playgroud)

是我试图不允许的设计?如果是这样,为什么?如果没有,我该怎么办?

注意:gcc接受所有这些.

c++ pointers clang constexpr c++11

29
推荐指数
2
解决办法
6195
查看次数

constexpr和一个带有重新解释强制转换的静态const void指针的初始化,哪个编译器是对的?

考虑以下代码:

struct foo {
  static constexpr const void* ptr = reinterpret_cast<const void*>(0x1);
};

auto main() -> int {
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的例子在g ++ v4.9(Live Demo)中编译得很好,但它无法在clang v3.4(Live Demo)中编译并生成以下错误:

错误:constexpr变量'ptr'必须由常量表达式初始化

问题:

  • 根据标准,哪两个编译器是正确的?

  • 声明这种表达的正确方法是什么?

c++ gcc clang constexpr c++11

17
推荐指数
2
解决办法
3691
查看次数

标签 统计

c++ ×2

c++11 ×2

clang ×2

constexpr ×2

gcc ×1

pointers ×1