About const references

V

vineoff

When you should not or can't use const references?

Like

void f ( const Foo& b) ;

or

int main() { const int& r = 5; }
 
R

roberts.noah

vineoff said:
When you should not or can't use const references?

Like

void f ( const Foo& b) ;

Use a const reference when you need access to data or query methods in
the object but won't be "changing" that object. By using a const
reference you are saying, "I am not going to change this object." Of
course you can violate that by const_cast and the object can have
"mutable" variables that can change in a const reference. It is a
contract that you make with clients of your class or method.

It also allows constant references to be passed in where otherwise they
can't. But this is really a concequence of the contract made by the
const keyword...you can't use anything on that object that could change
the object so you can't use non-const methods or pass it to a function
that would cause the constness of the object to go away.
or

int main() { const int& r = 5; }

That doesn't look legal.
 
V

Victor Bazarov

vineoff said:
When you should not or can't use const references?

You should use references as arguments most of the time, unless there is
a compelling reason to use a pointer or pass by value.

You should use references as members when the lifetime of the owner of
that member does not exceed (ever) the lifetime of the referred object and
the association is never broken (or changed) during the lifetime of the
owner object. And of course, we assume no containment here, just the
association.

You should use references as return value types so that function calls
could be chained or the result could be used in an expression.

Now, as to 'const', you should always qualify your objects 'const' if you
don't expect to change them.

Now, combine the negative of those statements and you will get the reasons
_not_ to use references to const. For example, if in a situation calling
for *association* between objects you expect to break that association at
some moment during the lifetime of the *referring* object, then you should
not use a reference at all, and should use a pointer.
Like

void f ( const Foo& b) ;

This is a very common idiom.
or

int main() { const int& r = 5; }

This use of references while valid, is not warranted. You should simply
write

int main() { const int r = 5; }

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top