c++ - 是否为 n 创建了单独的内存位置,或者 m 或 n 都指向同一位置?

标签 c++

谁能告诉我这几行代码在做什么? m 的值是否被复制到n 的内存位置?或者n也指向与m相同的地址?又如何?

int m=5;
int &n=m;

最佳答案

int m = 5;

此行创建一个 int 类型的变量,其中包含值 5

int& n = m;

此行创建对 m引用。您可以将其视为 m 的别名。所以这个指令:

n = 6;

实际上更改了m的值。

引用通常(但并非总是如此,请参阅 here )在内部实现为指针。编译器通常会在内存中保留一个位置,用于存储 m内存地址。这意味着以下代码段是等效的:

int main() {
    int m = 5;
    int& n = m; // Reference
    n = 6;
}
int main() {
    int m = 5;
    int* const n = &m; // Pointer const (meaning the held memory address 
                       // can't be changed, only the value at that address can be)
    *n = 6;
}

我个人只使用const引用,这意味着我无法修改正在引用的值的值。当我实际上想要修改引用的值时,我使用指针,因为我认为它们提供了更多的清晰度(它们基本上说“我不拥有这个值,这意味着当我修改它时,期望程序中其他地方的值已经改变。”)。

那么什么时候使用 const 引用呢?可以说,它们最常见的用例是通过引用传递函数参数。例如,将 std::string 对象传递给以下函数实际上是复制它,这对于大型对象来说可能非常昂贵。

#include <string>

void doStuffWithString(std::string str /* potentially expensive */) {
    // ...
}

相反,您可以通过 const 引用传递它,这意味着您不会将实际对象传递给函数,而是将 const引用它以防止不必要的复制。

#include <string>

void doStuffWithString(const std::string& str /* not expensive */) {
    // ...
}

如果我想修改正在传递的对象的值,我可以通过地址(使用指针)传递它。

#include <string>

void modifyString(std::string* str /* pointer */) {
    // ...
}

int main() {
    std::string hiMom("Hi mom!");
    modifyString(&hiMom); // Explicitly shows the caller that we're passing
                          // a pointer, meaning the value of hiMom might change
    return 0;
}

关于c++ - 是否为 n 创建了单独的内存位置,或者 m 或 n 都指向同一位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71410159/

相关文章:

c++ - 我是否需要使用内存屏障来保护共享资源?

c++ - 如何使用 Qt Camera 放大/缩小?

C++链表复制和克隆函数

c++ - std::thread 不是使用 Eclipse Kepler MinGW 命名空间 std 的成员

c++ - 使用 boost QT 和 mingw 的多线程

c++ - 带有 "source shellscript.sh"的 CLion

c++ - 如何克服 "undefined reference to _M_insert_aux()"?

c++ - 我怎样才能乘以非常大的数字 C++

c++ - 将 std::multimap 转换为 std::priority_queue

c++ - 有没有更有效的方法来替换这些多个 IF 语句?