Why pass by const reference instead of by value?

Many newbies ask these questions, “Why pass by const reference instead of by value in C++?”.

So in this post, I will give the answer to the question of why you should pass parameters in function by const reference instead of by value. I will also explain the difference between const reference and normal parameter (const T & rValue vs T value), where T is a type specifier.

You must have basic knowledge of reference and const, these are primary prerequisites of this question. So it is my recommendation that if you are learning C++ you must read the below articles.

 

Consider the below-mentioned functions.

Case1:

//passing reference with const
void validating(STestData value)
{
    //doing some task
}


Case2:

//passing by value
void validating(const STestData& rValue)
{
    //doing some task
}

Where STestData is a structure.

/**
 * struct to store some value and Index.
 */
struct STestData
{
    unsigned int index;
    unsigned int data[1024];
};

 

Both functions are doing the same task and both are preventing changing the value of passed parameters.

Now the question is coming that if both functions are doing the same task, then what is the difference in both functions?

Don’t worry at the ending you will get the answer to the question. Let’s understand both functions.

Case 1:

void validating(STestData value);

In case 1, we are passing the ‘normal’ parameter. It means you are passing the parameter by value. Passing parameter by value creates a copy of the parameter you pass. Also, you would suffer the expense of copying the passed object.

Case 2:

void validating(const STestData& rValue);

In case 2, we have used the const reference so here we will use only reference. Here neither a temporary object will create and also it avoids making an unnecessary copy.

 

Note: The difference between both functions will be more prominent when you pass a big struct/class.

 

Now I believe you have an understanding of why we should use const reference instead of the pass-by-value.

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *