如何在寄存器中存储C ++变量 [英] How to store a C++ variable in a register

查看:91
本文介绍了如何在寄存器中存储C ++变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清一下有关寄存器变量存储的一点:$ b​​ $ b是否有一种方法可以确保,如果我们在代码中声明了一个寄存器变量,则只能将其存储在寄存器中?

I would like some clarification regarding a point about the storage of register variables: Is there a way to ensure that if we have declared a register variable in our code, that it will ONLY be stored in a register?

#include<iostream>

using namespace std;

int main()
{
    register int i = 10;// how can we ensure this will store in register only.
    i++;
    cout << i << endl;
    return 0;
}


推荐答案

您不能。只是向编译器提示,该变量被大量使用。以下是C99的措辞:

You can't. It is only a hint to the compiler that suggests that the variable is heavily used. Here's the C99 wording:


声明具有存储类指定符 register 建议尽快访问该对象。

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.

这是C ++ 11的措辞:

And here's the C++11 wording:


一个寄存器说明符表示实现将声明的变量大量使用。 [注意:提示可以忽略,在大多数实现中,如果使用变量的地址,则将忽略提示。不建议使用此用法(请参阅D.2)。 —尾注]

A register specifier is a hint to the implementation that the variable so declared will be heavily used. [ Note: The hint can be ignored and in most implementations it will be ignored if the address of the variable is taken. This use is deprecated (see D.2). —end note ]

实际上,已弃用寄存器存储类说明符在C ++ 11(附件D.2)中:

In fact, the register storage class specifier is deprecated in C++11 (Annex D.2):


使用寄存器关键字作为存储类说明符(7.1.1)。

The use of the register keyword as a storage-class-specifier (7.1.1) is deprecated.

您不能使用C中的寄存器变量的地址,因为寄存器没有地址。在C ++中,取消了此限制,并保证了地址的获取以确保变量不会在寄存器中结束。

Note that you cannot take the address of a register variable in C because registers do not have an address. This restriction is removed in C++ and taking the address is pretty much guaranteed to ensure the variable won't end up in a register.

许多现代编译器只是忽略了<$ C ++中的c $ c> register 关键字(当然,除非以无效的方式使用它)。与 register 关键字有用时相比,它们在优化方面要好得多。我希望利基目标平台的编译器会更认真地对待它。

Many modern compilers simply ignore the register keyword in C++ (unless it is used in an invalid way, of course). They are simply much better at optimizing than they were when the register keyword was useful. I'd expect compilers for niche target platforms to treat it more seriously.

这篇关于如何在寄存器中存储C ++变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆