C ++通过const指针或对const指针的引用传递 [英] c++ passing by const pointer or reference to const pointer

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

问题描述

我正在学习c ++,最近我读了一本书,建议您在可能的情况下(如果基本对象不会被更改)使用对const的引用。

I am learning c++, recently i read a book which gives a suggestion that you should use reference to const when possible (if base object will not be changed).

我有一个问题,如果可能的话,应该将引用传递给const指针而不是const指针,因为引用可以防止复制。如果不是,我什么时候应该使用对const指针的引用。

I have a question that should you pass reference to const pointer instead of const pointer, when possible, as reference prevents copied. If not when should i use reference to const pointer.

例如:

Node(..., Node *const next = nullptr);

OR

Node(..., Node* const& next = nullptr);


推荐答案

通过值引用传递const引用是一种好习惯(这会导致参数的复制)是一项繁重的操作。

Passing by const reference is good practice when passing by value (that causes copying of parameters) is a heavy operation.

例如,当您将具有某些属性的类传递给函数时,最好通过const引用传递它,另一方面,如果您要传递 int 之类的类型或仅使用指针,则最好不要使用引用,因为这样会由于取消引用过程而失去性能。

For example when you are passing a class with some properties to a function it's better to pass it by const reference, In other hand if your are passing types like int or just a pointer it's better not to use references because then you loos performance due to de-reference process.

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

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