Home > Article > Backend Development > When to Pass by Reference or Pointer in C : A Guiding Principle?
Passing by Reference or Pointer in C : A Guiding Principle
In C , understanding when to employ passing by reference and when to use pointers is crucial. This practice can lead to efficient and error-free code.
General Situations
Passing a std::string to a function:
Passing a tr1::shared_ptr to a function:
Pointers vs. References
Passing by reference offers consistency, as every object can be treated as a reference. However, passing by pointer provides the flexibility to handle nullptrs and literals.
Snippet Analysis
The given snippet:
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);
highlights the need to consider the properties of both references and pointers:
Rule of Thumb
Ultimately, the appropriate choice depends on the specific requirements. As a guiding principle, consider:
The above is the detailed content of When to Pass by Reference or Pointer in C : A Guiding Principle?. For more information, please follow other related articles on the PHP Chinese website!