returning const references/pointers from functions?

P

Protoman

When would you return a const reference/pointer from a function instead
of either the object itself, or a non constreference/pointer? And when
would you need to return a reference or pointer at all, instead of the
object itself?
 
?

=?iso-8859-1?Q?Ali_=C7ehreli?=

Protoman said:
When would you return a const reference/pointer from a function instead
of either the object itself,

I would return a const reference/pointer to avoid "premature pessimization"
but only if the object is alive even after the function returns.

If the object is non-copyable there is no other way than returning a
reference/pointer.
or a non constreference/pointer?

If the caller should be allowed to modify the object through the returned
reference/pointer.
And when
would you need to return a reference or pointer at all, instead of the
object itself?

You cannot return the object itself. You can either return a
reference/pointer to it, or you can return a copy of it.

When you need to work on a specific object, not a copy of it, you have to
return a reference/pointer.

Ali
--
Plug: ACCU's Silicon Valley Chapter meets on second Tuesdays. The meetings
are open to public and free of charge. Please come tonight for a talk on
Ada:

http://accu-usa.org/index.html
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top