how to choose value or pointer or reference?
when I code in c++, I don't have a clean idea when to choose each one?
Is there one priority or rule when choosing?
how to choose value or pointer or reference?
when I code in c++, I don't have a clean idea when to choose each one?
Is there one priority or rule when choosing?
You use a value when
You use pointers or references when
You decide between a pointer and a reference using a simple rule: if there are situations where your referenced object does not exist, or the same variable must refer to different objects throughout its lifetime, use a pointer; otherwise, use a reference.
I'll try, just for others to correct me:
If it really can't be null, and you don't want to store it, and it's not primitive, use reference; If you don't need to change it, use const reference.
Otherwise, if you need to change it, or to store it, use pointer (better: smart pointers).
If it's not primitive, use const
pointer.
If you need runtime polymorphism, you must not use pass-by-value.
Otherwise, use pass by value. use int
and not const int&
.
If you are writing a template, remember that passing by value (or copying in any way) implies a working copy-constructor as a constraint on the type. references might work wierd if the type is an array (or a string-literal).
I'll give a small round-up of what I think is good practise concerning the selection of a type derived from arbitary T.
template <typename _T>
void CALLED (_T B) { /* _STUFF_ */ }
template <typename T>
void CALLER (void)
{
T A;
typedef T TYPE;
CALLED<TYPE>(A);
}
TYPE can be one of the following:
T
(value type),T&
(reference), T
const & (reference to const T),T*
(pointer), T const *
(pointer to const T), T const * const
(const pointer to const T), T * const
(const pointer to non-const T)Note: For the pointer types the call statement would change to CALLED<TYPE>(&A);
.
CALLED()
is intended to have a valid objectThis should imho be somehow "default".
Guarantee to conserve A(^) | no | yes | yes | yes | Alteration of B desired | yes | yes | no | no | sizeof(T) > sizeof(T*) | yes/no | yes/no | yes | no | ------------------------------------------------------------------------- TYPE (of B) | T& | T | T const & | T const |
(^): A "no" in this row can also mean that you want to alter A on purpose. I'll just have the optimal type depicted that conservation of A is guaranteed if this is not the case.
CALLED()
can (and does) depict whether it gets a valid objectSince it is not very smart to bind a references to NULL and since a value parameter will always try to obtain an object, we'll have to stick to pointers here. Since call by value does not make much sense here, size of T is irrelevant.
Guarantee to conserve A(=*B) | no | yes | yes | no | Alteration of B | no | no | yes | yes | ----------------------------------------------------------------------------------- TYPE | T* const | T const * const | T const * | T* |