c++ - 为什么要创建 register 关键字?

标签 c++ c c++11 language-lawyer

阅读时Keywords That Aren't (or, Comments by Another Name)作者 Herb Sutter 我遇到了以下几行:

That's right, some keywords are semantically equivalent to whitespace, a glorified comment.

We've seen why the C++ language treats keywords as reserved words, and we've seen two keywords —auto and register — that make no semantic difference whatsoever to a C++ program. Don't use them; they're just whitespace anyway, and there are faster ways to type whitespace.

如果auto(可能不在C++11中)和register这样的关键字没有值(value),那么为什么要创建和使用它们呢?

如果在变量之前包含 register 没有任何区别

#include<stdio.h>
int main(){
    register int a = 15;
    printf("%d\n%d\n",&a,a);
    return 0;
}

为什么上面的程序会报错?

test_register.c: In function ‘main’:

test_register.c:4:2: error: address of register variable ‘a’ requested

printf("%d\n%d\n",&a,a);

以下程序在 C++ 中运行。

#include<iostream>
int main(){
    register int a = 15;
    std::cout<<&a<<'\n'<<a;
    return 0;
}

最佳答案

注册

在 C 中,register 存储类被用作编译器的提示,表示 a variable should be preferentially stored in a register .请注意,将 register 变量存储在实际寄存器中的提示可能会或可能不会兑现,但在任何一种情况下,相关限制仍然适用。见 C11, 6.7.1p6(强调我的):

A declaration of an identifier for an object with storage-class specifier register suggests that access to the object be as fast as possible. The extent to which such suggestions are effective is implementation-defined.[footnote 121]

[footnote 121] The implementation may treat any register declaration simply as an auto declaration. However, whether or not addressable storage is actually used, the address of any part of an object declared with storage-class specifier register cannot be computed, either explicitly (by use of the unary & operator as discussed in 6.5.3.2) or implicitly (by converting an array name to a pointer as discussed in 6.3.2.1). Thus, the only operators that can be applied to an array declared with storage-class specifier register are sizeof and _Alignof.

在 C++ 中,它只是一个未使用的保留关键字,但可以合理地假设它是为了与 C 代码的语法兼容而保留的。

自动

在 C 中,auto 存储类定义了一个自动存储的变量,但是自从 function-local variables are auto by default 以来它通常不被使用。 .

同样,可以合理地假设它最初只是为了语法兼容性而转移到 C++ 中,尽管后来它有了自己的含义 (type inference)。

关于c++ - 为什么要创建 register 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37456494/

相关文章:

c++ - 从 Boost.ASIO 的套接字类中分离一个本地套接字

c++ - 将 float 与小数点后三位进行比较

c - 使用 strtok 解析字符串数组

c - 指向指针地址的指针

c++ - 在共享缓冲区内存中创建一个::std::string 对象

c++ - 初始化列表作为类构造函数的参数

C++:检查是否引用了地址

c++ - 如何使用opengl使点闪烁?

c - 如何将数据从 GHashTable 存储到 C 中的结构

c++ - 用于新运算符分配的公共(public)内存