Re: const ref vs. pointer
- From: Ulrich Eckhardt <eckhardt@xxxxxxxxxxxxxx>
- Date: Thu, 02 Nov 2006 12:35:06 +0100
Luca wrote:
1. Which one is the best: Returning member variables of the class by const
ref or returning by pointer?
e.g.:
Employee* GetEmployee() const;
Employee& GetEmployee() const;
You are not returning a reference-to-const here.
2. Which one is best: Passing a variable by const ref or by pointer?
e.g.:
void SetSalary(Employee* e);
void SetSalary(const Employee& e);
Passing a pointer and passing a reference-to-const are two totally different
things. Anyhow, I'll take your question as "What is the difference between
passing a pointer and a reference?" instead.
When I see a pointer, I have two thoughts:
1. It can be null. IOW, I can pass NULL to a function and a function
might return NULL, which I need to check for.
2. Who owns the object pointed to? Only documentation can answer that.
The only exception is pointers to string literals, i.e. 'char const*'
and 'wchar_t const*'. I still parse these as strings. However, there rarely
is a reason to use those, use std::wstring instead.
Some more guidelines:
If you always pass an object, (i.e. a null pointer would be invalid) you
should use a reference instead. It implicitly documents the requirement
that you always pass an object.
If you only sometimes return an object (in particular if that object is a
value type) consider using boost::optional<object> instead. See the
examples for more info on this very useful wrapper.
If the object pointed to is transferred, i.e. the receiving end gets
ownership and is responsible for releasing the object you should use
std::auto_ptr instead. When used properly, std::auto_ptr guarantees
exclusive ownership, thus making the question who deletes what moot.
If the object is for inspection by the receiver and ownership is shared, you
should use e.g. boost::shared_ptr<object> or similar smart pointer. This
eases the burden of proper deallocation when you don't have to ask yourself
if some other object might still make use of the pointer. In simple cases I
find a raw pointer plus documentation sufficient here, too.
Other than all that, never ask a question involving the term "best" without
defining what exactly you mean with it. ;)
cheers
Uli
.
- Follow-Ups:
- Re: const ref vs. pointer
- From: Ben Voigt
- Re: const ref vs. pointer
- References:
- const ref vs. pointer
- From: Luca
- const ref vs. pointer
- Prev by Date: Re: SMP - dual/triple/?? processor programming
- Next by Date: Re: warning C4238 : cast reference in void*
- Previous by thread: const ref vs. pointer
- Next by thread: Re: const ref vs. pointer
- Index(es):
Relevant Pages
|