指针可以指向 CPU 寄存器吗? [英] May a pointer ever point to a cpu register?

查看:78
本文介绍了指针可以指向 CPU 寄存器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个指针是否可能指向一个 cpu 寄存器,因为在这种情况下它可能不会,尽可能使用引用而不是指针会给编译器做一些优化的机会,因为被引用的对象可能驻留在某个寄存器中,但指针指向的对象可能不是.

I'm wondering if a pointer may point to a cpu register since in the case it may not, using reference instead of pointer where possible would give compiler opportunity to do some optimizations because the referenced object may reside in some register but an object pointed to by a pointer may not.

推荐答案

一般来说,CPU 寄存器没有内存地址,尽管 CPU 架构可以使它们可寻址(我不熟悉任何 - 如果有人知道,我很感激评论).但是,C 中没有标准方法来获取寄存器的地址.事实上,如果您使用 register 存储类标记变量,则不允许使用 & 运算符获取该变量的地址.

In general, CPU registers do not have memory addresses, though a CPU architecure could make them addressable (I;m not familar with any - if someone knows of one, I'd appreciate a comment). However, there's no standard way in C to get the address of a register. In fact if you mark a variable with the register storage class you aren't permitted to take that variables address using the & operator.

关键问题是别名——如果编译器可以确定一个对象没有别名,那么它通常可以执行优化(无论对象是通过指针还是引用访问).我认为使用指针上的引用不会获得任何优化好处(通常无论如何).

The key issue is aliasing - if the compiler can determine that an object isn't aliased then it can generally perform optimizations (whether the object is accessed via a pointer or a reference). I don't think you'll get any optimization benefit using a reference over a pointer (in general anyway).

但是,如果您将对象复制到局部变量中,那么编译器可以更轻松地确定没有局部别名,前提是您没有传递临时地址.这是一个可以帮助编译器优化的案例;但是,如果复制操作成本很高,最终可能不会有回报.

However if you copy the object into a local variable, then the compiler can make an easier determination that there's no aliasing of the local assuming you don't pass the temporaries address around. This is a case where you can help the compiler optimize; however if the copy operation is expensive, it might not pay off in the end.

对于适合 CPU 寄存器的内容,复制到临时文件通常是一个好方法 - 编译器非常擅长将这些内容优化为寄存器.

For something that would fit in a CPU register, copying to a temp is often a good way to go - compilers are great at optimizing those to registers.

这篇关于指针可以指向 CPU 寄存器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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