Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ passing by const pointer or reference to const pointer

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).

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.

e.g:

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

OR

Node(..., Node* const& next = nullptr);
like image 383
Đào Thiện Tuấn Avatar asked Oct 20 '25 06:10

Đào Thiện Tuấn


2 Answers

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

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.

like image 55
HMD Avatar answered Oct 21 '25 21:10

HMD


Since references essentially are pointers there is no performance gain in passing pointers by reference.

like image 27
Johan Avatar answered Oct 21 '25 21:10

Johan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!