C++ – When to Pass by Reference vs Pointer

c++

Common Situations:

  1. Passing std::string to a function foo(std::string*) or foo(std::string&);
  2. Passing tr1::shared_ptr to a function foo(tr1::shared_ptr* ptr) or foo(tr1::shared_ptr& ptr);

In general, what is a good practice. I always get confused. At first, passing everything as references seems consistent, however it is not possible to pass in Literals as references or NULLs as references.

Similarly, having everything as pointers seems good, but having then I have to worry that pointers might be pointing to NULL and check for those conditions in the beginning of that function.

Do you think the following snippet is good?

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <tr1/memory>
#include <algorithm>
using namespace std;
using namespace std::tr1;

int main(){
        map<string, shared_ptr<vector<string> > > adjacencyMap;
        vector<string>* myFriends = new vector<string>();
        myFriends->push_back(string("a"));
        myFriends->push_back(string("v"));
        myFriends->push_back(string("g"));
        adjacencyMap["s"] = shared_ptr<vector<string> >(myFriends);
        return 0;
}

Thanks
Ajay

Best Answer

A good rule of thumb: "Use references when you can and pointers when you have to".

Related Question