reference or pointer in parameter list - which is prefereable?

M

Maksim Kasimov

i have two functions and both of them are to make changes into object field or get some results into caller function:

void FooFunc1(FooClass& a)
{ ...

void FooFunc2(FooClass* a)
{ ...

or

void FooFunc3(int& a)
{ ...

void FooFunc4(int* a)
{ ...


in what cases it is prefereble to use reference or pointer in parameter list?

many thanks.
 
I

Ian Collins

Maksim said:
i have two functions and both of them are to make changes into object
field or get some results into caller function:

void FooFunc1(FooClass& a)
{ ...

void FooFunc2(FooClass* a)
{ ...

or

void FooFunc3(int& a)
{ ...

void FooFunc4(int* a)
{ ...


in what cases it is prefereble to use reference or pointer in parameter
list?
I'd say neither. I'd use a smart pointer type, but that's my style.

There are may arguments for and against both, look back through the
group archives.
 
R

Roland Pibinger

I'd say neither. I'd use a smart pointer type, but that's my style.

"Smart" pointers should _never_ be used as function parameters!

Best wishes,
Roland Pibinger
 
R

Roland Pibinger

i have two functions and both of them are to make changes into object field or get some results into caller function:

void FooFunc1(FooClass& a)
{ ...

void FooFunc2(FooClass* a)
{ ...

or

void FooFunc3(int& a)
{ ...

void FooFunc4(int* a)
{ ...


in what cases it is prefereble to use reference or pointer in parameter list?

Use references when you can pointers when you must (IIRC, this is a
FAQ). Pointers are only necessary when you also need to pass 0 (NULL)
to the function. The latter probably indicates a design problem
anyway.

Best wishes,
Roland Pibinger
 
I

Ian Collins

Squeamizh said:
What if the parameter isn't dynamically allocated?
Then you can't pass it.

I guess I've been working in an environment where every object is some
form of smart pointer, I'd overlooked the obvious!

I tend to faviour references in the general case.
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top