当传递指针优先于C ++中的传递引用? [英] When pass-by-pointer is preferred to pass-by-reference in C++?

查看:135
本文介绍了当传递指针优先于C ++中的传递引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以想象一种情况,其中输入参数可以为NULL,以便优先传递指针,但不传递引用。

I can imagine one case, in which the input parameter could be NULL so that pass-by-pointer is preferred but not pass-by-reference?

任何人添加更多的情况?

Can anybody add more cases?

推荐答案

有些像传递指针更好地在被传递的对象实际上改性。当对象通过引用传递时,为了避免对象的副本,它们使用pass-by-const引用,但不会在函数中更改。

Some like pass-by-pointer better in cases where the object being passed is actually going to be modified. They use pass-by-const-reference when the object is being passed by reference in order to avoid a copy of the object, but will not be changed in the function.

在图中,采用以下函数:

In illustration, take the following functions:

int foo(int x);
int foo1(int &x);
int foo2(int *x);

现在在代码中,我执行以下操作:

Now in the code, I do the following:

int testInt = 0;

foo(testInt);   // can't modify testInt
foo1(testInt);  // can modify testInt

foo2(&testInt); // can modify testInt



在调用foo vs foo1时,从调用者的角度看不是很明显程序员读取代码),函数可以修改testInt而不必查看函数的签名。看看foo2,读者可以很容易地看到该函数可能实际上修改了testInt的值,因为该函数接收到参数的地址。注意,这并不保证对象被实际修改,但这是在引用与指针的使用中一致的地方有帮助。一般来说,如果你想一致遵循这个指南,你应该总是传递const引用当你想避免副本,并通过指针,当你想要能够修改对象。

In calling foo vs foo1, it's not apparent from the callers perspective (or a programmer reading the code) that the function can modify testInt without having to look at the signature of the function. Looking at foo2, a reader can easily see that the function may in fact modify the value of testInt because the function is receiving the address of the parameter. Note that this doesn't guarantee the object is actually modified, but that's where being consistent in the use of references vs. pointers helps. In general, if you want to follow this guideline consistently you should always pass const references when you want to avoid copies, and pass by pointer when you want to be able to modify the object.

这篇关于当传递指针优先于C ++中的传递引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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