Sign in to follow this  

Question about constants

This topic is 3811 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In this particular situation, it is completely useless, since the returned value would be a temporary value (and thus, wouldn't be modifiable) anyway.

However, you may wish to return a value by reference (perhaps to avoid creating a copy of the value, or perhaps because you want changes applied to that value to be received by the holder of the return value) but do not wish to let the one who called the function modify the referenced value.

A typical example is v.front() when v is a const std::vector<int> (at which point, the function returns a const int &).


void foo(const std::vector<int> & v)
{
// Function foo may not alter the vector which
// it receives, and this includes altering the
// value of its first element!
const int & i = v.front();
std::cout << i << "\n";

// However, it's possible to alter the vector
// through a variable other than 'v', perhaps
// if the original vector is a global variable
// that was passed as an argument:
g_v[0] = 100;

// And now, this outputs 100.
std::cout << i << "\n";
}

Share this post


Link to post
Share on other sites

This topic is 3811 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this