[英]Bison: $$ and $1 point to the same memory location (union YYSTYPE of two pointer types)
[英]Is separate memory location created for n or both m or n point to the same location?
任何人都可以让我清楚这些代码行在做什么吗? m 的值是否被复制到n
的 memory 位置? 或者n
也指向与m
相同的地址? 如何?
int m=5;
int &n=m;
int m = 5;
上面一行创建了一个int
类型的新变量,并为其赋值5
。
int &n = m;
这创建了一个int
类型的引用变量并将m
分配给它。 这意味着n
基本上是m
的另一个名称,如果n
的值改变, m
的值也会改变。 它有点像pointers
,但比pointers
更高级。
int m = 5;
此行创建一个类型为int
的变量,其中包含值5
。
int& n = m;
此行创建对m
的引用。 您可以将其视为m
的别名。 所以这个指令:
n = 6;
实际上改变了m
的值。
引用通常(但并非总是如此,请参见此处)在内部实现为指针。 编译器通常会在 memory 中保留一个位置,用于存储m
的memory 地址。 这意味着以下代码段是等效的:
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
引用呢? 可以说,他们最常见的用例是通过引用传递 function 参数。 例如,将一个std::string
对象传递给以下 function 实际上是复制它,这对于大对象来说可能非常昂贵。
#include <string>
void doStuffWithString(std::string str /* potentially expensive */) {
// ...
}
相反,您可以通过const
reference传递它,这意味着您不会将实际的 object 传递给 function,而是传递对它的const
引用以防止不必要的复制。
#include <string>
void doStuffWithString(const std::string& str /* not expensive */) {
// ...
}
如果我想修改传递的 object 的值,我会通过地址(使用指针)传递它。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.