[英]Confusion over C++ pointer and reference topic
What is the difference between the following parameter passing mechanisms in C++? C ++中以下参数传递机制之间的区别是什么?
void foo(int &x)
void foo(int *x)
void foo(int **x)
void foo(int *&x)
I'd like to know in which case the parameter is being passed by value or passed by reference. 我想知道在哪种情况下参数是通过值传递还是通过引用传递。
void foo(int &x)
passes a reference to an integer. 将引用传递给整数。 This is an input/output parameter and can be used like a regular integer in the function. 这是一个输入/输出参数,可以像函数中的常规整数一样使用。 Value gets passed back to the caller. 值被传回给调用者。
void food(int *x)
passes a pointer to an integer. 将指针传递给整数。 This is an input/output parameter but it's used like a pointer and has to be dereferenced (eg *x = 100;
). 这是一个输入/输出参数,但其用法类似于指针,必须取消引用(例如*x = 100;
)。 You also need to check that it's not null. 您还需要检查它是否不为空。
void foo(int **x)
passes a pointer to a pointer to an integer. 将指针传递给指向整数的指针。 This is an input/output parameter of type integer pointer. 这是整数指针类型的输入/输出参数。 Use this if you want to change the value of an integer point (eg *x = &m_myInt;
). 如果要更改整数点的值,请使用此值(例如*x = &m_myInt;
)。
void foo(int *&x)
passes a reference to a pointer to an integer. 将引用传递给指向整数的指针。 Like above but no need to dereference the pointer variable (eg x = &m_myInt;
). 像上面一样,但无需取消引用指针变量(例如x = &m_myInt;
)。
Hope that makes sense. 希望有道理。 I would recommend using typedefs to simplify the use of pointers and reference symbols. 我建议使用typedefs来简化指针和引用符号的使用。
Just adding: I think your spacing is misleading. 只需补充:我认为您的间距会误导您。 Maybe things get a bit clearer if you change it. 如果您进行更改,情况可能会变得更加清晰。
The , &, * and so on is part of the type, so keep it with the type: ,&,*等是该类型的一部分,因此请保留该类型:
void foo(int& x)
void foo(int* x)
void foo(int** x)
void foo(int*& x)
int& is an reference to an int, int* is a pointer to an int, int** is a pointer to an pointer to an int, and so on. int&是对int的引用,int *是对int的指针,int **是对int的指针,依此类推。 You still need to read the types from right to left - int*& being a reference to an pointer to an int. 您仍然需要从右到左读取类型-int *&是对指向int的指针的引用。 But that's consistent. 但这是一致的。
I think this is easier to read and represents better what is meant. 我认为这更容易阅读,代表的含义更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.