c++ - const 引用参数和函数上下文中的 const 参数之间的区别

标签 c++

在调用函数时,我倾向于使用 const 引用参数,假设这会很有效,因为不会创建相同的拷贝。我不小心将以前具有 const 引用 参数的函数中的函数参数更改为 const,我发现编译后代码大小减少了。

为了检查这一点,我研究了 MWE 的组件。 :

#include <cstdint>

void foo(const int n)
{
    int a = n + 1;
}

void foo(const int& n)
{
    int a = n + 1;
}

在生成的汇编代码的第 19 行,在比较 void foo(const int& n) 的情况下,我看到了一个额外的步骤 ldr r3, [r3]void foo(const int n)。我认为这是对变量n的引用(我可能是错的,请原谅我)。

所以,我的问题是,为什么通过引用传递时代码会更大,以及什么方法是有效的?

最佳答案

引用可以理解为介于名称别名和指针之间的东西。 来自 What are the differences between a pointer variable and a reference variable? :

A compiler keeps "references" to variables, associating a name with a memory address. Its job is to translate any variable name to a memory address when compiling. When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null". A variable cannot be, and not be at the same time. Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.

  • 在 32 位机器上,指针 有 4 个字节(4*8 = 32 位),而在 64 位机器上, >pointer 有 8 个字节(8*8 = 64 位),因为这是单个内存地址的大小。

  • 在 32 位机器上,intlong 均为 4 字节(32 位)数量。 在大多数 64 位系统上,long 变为 8 字节(64 位),int 仍为 32 位(4 字节)。

[说到基本类型,char 的大小在 C++ 标准中明确固定为 1 字节(或 CHAR_BIT = 8 位)。]

鉴于将 const 引用 作为函数参数传递,需要编译器挖掘所引用变量的内存地址,以防该变量是基本类型,例如 int > 或 char 内存中的挖掘(pointer 是 8 个字节)将比按值传递变量本身(int 为 4 个字节)更昂贵code>,char 1 个字节)。

问题是关于const引用传递的参数的效率。 当然,通过非常量引用接受参数的函数具有以下优点(与效率无关):当控制权返回时,允许对引用变量的修改持续存在给调用者。

关于c++ - const 引用参数和函数上下文中的 const 参数之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73225886/

相关文章:

c++ - 从 C/C++ 中的 64 位值中获取 32 位字而不用担心字节序

c++ - 在 std::map 中返回 std::vector

c++ - 防止 Visual C++ 内联函数

c++ - 计算这个字符串匹配函数的大 O 复杂度?

c++ - 在 Mac OS X 上安装 C++ Armadillo 库

c++ - 来自绑定(bind)方法的原始函数指针

c++ - 不可读的文件

c++ - 使用 STL 排序就地排序表

c++ - 从整数 vector 返回一个无符号长整数 C++

c++ - 指向成员函数的指针作为全局函数的参数