c++ - 指针类型是文字类型吗?

标签 c++

标量类型定义为

Trait class that identifies whether T is a scalar type. A scalar type is a type that has built-in functionality for the addition operator without overloads (arithmetic, pointer, member pointer, enum and std::nullptr_t).

It inherits from integral_constant as being either true_type or false_type, depending on whether T is a scalar type, no matter its const and/or volative qualification.

表示指针是标量类型。

现在,如果我们转到文字类型的定义:

A type is a literal type if it is:

  • a scalar type; or
  • a reference type; or
  • an array of literal type; or -a class type (Clause 9) that has all of the following properties:
    • it has a trivial destructor,
    • every constructor call and full-expression in the brace-or-equal-initializers for non-static data members (if any) is a constant expression (5.19),
    • it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and
    • all of its non-static data members and base classes are of literal types.

现在,结合以上 2 条语句,这意味着指针是字面量类型。但是指针不能是 constexpr。有人可以澄清一下吗?

进一步看下面代码:

int a = 7;
constexpr int *pointer1 = &a;
int main ()
{
  int b = 4;
  constexpr int *pointer2 = &b;
}

指针 1 没问题,但指针 2 出错。这是否意味着指向全局的指针可以,但指向自动变量的指针就不行?标准是否在任何地方提及这一点?

最佳答案

指针是文字类型。它们在特定条件下可以是 constexpr:

[expr.const] 6

... [a pointer is constexpr if] it contains the address of an object with static storage duration, the address past the end of such an object (5.7), the address of a function, or a null pointer value.

(其中“具有静态存储持续时间的对象”表示全局或静态对象,或此类对象的子对象。)

A demo:

int x;

int main()
{
    constexpr int *ptr = &x; // Compiles.

    // Doesn't compile: `error: '& foo' is not a constant expression`
    // int foo;
    // constexpr int *bar = &foo;
}

显然 GCC(带有 -pedantic-errors -std=c++11/14/17)愉快地接受了- range constexpr pointer arithmetic: constexpr int *ptr = &x - 10;,这对我来说似乎是个错误。

关于c++ - 指针类型是文字类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50466400/

相关文章:

c++ - 如何在 Python 中实现 C++ 类,由 C++ 调用?

c++ - 通过 C++ 的编译时安全更改 QML 属性

c++ - 在 QListWidget 中,我如何根据其数据成员检查 QListWidgetItem 是否已经存在

c++ - 在嵌入式 x86 程序集中添加数组?

c++ - 捕获 boost 序列化存档异常

c++ - 为什么与 C 相比,链接器在 C++ 中的任务更艰巨?

c++ - 声明/定义作为 C 和 C++ 中的语句

c++ - Linux 上的共享库版本和可执行文件

c++ - 相同功能的不同实现(c/c++)

c++ - 运算符重载<<错误