Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use const T& instead of const T or T&

Tags:

c++

I always use const T& to pass a class to a function. Like this:

void foo(const MyType& p)
{
  //...
}

But now I'm confused, why not pass a const T or a T& to a function?

By the way, for built-in types, like int, long long, double, why const T is better than const T& (I remember I've read in Effective C++)

Thanks for answering my questions.

like image 589
abcdabcd987 Avatar asked Jan 15 '23 22:01

abcdabcd987


1 Answers

You could pass any of the three (const T, T&, or const T&). They all have different meanings. Up to you whether you want to pass a copy of the object that cannot be modified, a non-const reference to the object, or a const reference to the object. What you choose depends on the semantics of your code. Overall, you would want to choose const T& over const T in order to refrain from having to copy the value over from the caller to this function (save time and memory). Moreover (according to this helpful link), you would want to use const T& over T& whenever you want to refrain from changing neither the value nor the state of the passed reference. This can prevent silly and overlooked coding errors, such as changing a field for testing purposes.

For your question about passing as a parameter a reference to a const primitive type, see this: C++ and QT4.5 - is passing a const int& overkill? Does pass by reference helps in signals/slots?

like image 170
ecbrodie Avatar answered Jan 29 '23 11:01

ecbrodie