Pointers as arguments in functions

Jun 3, 2010 at 11:25am
Hi all,

I am still pretty confused about pointers. Say that your function accepts the following variables:

function_(shared_ptr<Pink>& pi, shared_ptr<Red>& re, Cars* shape, Animals* ncb)

Now, do not care about the names you see. It is just an example. My questions is: why in some cases we choose the pointer using the asterisk and in other cases we choose the reference? What would be the reason behind it?

Thanks in advance for you explanations.

Chiara
Last edited on Jun 3, 2010 at 11:25am
Jun 3, 2010 at 12:50pm
Other than syntax, the main difference between pointers and references is that references cannot be left unassigned. A function that takes a reference doesn't need to check that that reference is pointing to something, unlike with pointers.
1
2
3
4
5
void f(T *p,T &r){
    if (!p)
        return;
    //r can't be null
}
Jun 3, 2010 at 1:42pm
In the case you cite, you are passing smart pointer objects by reference and raw pointers as, well, pointers. Smart pointers are not pointers. Rather they are objects with a pointer-like interface that are used to manage the life cycle of heap-allocated objects.
Topic archived. No new replies allowed.