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> > adjacencyMap; vector * myFriends = new vector (); myFriends->push_back(string("a")); myFriends->push_back(string("v")); myFriends->push_back(string("g")); adjacencyMap["s"] = shared_ptr >(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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3