"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > When to Pass by Reference or Pointer in C++: A Guiding Principle?

When to Pass by Reference or Pointer in C++: A Guiding Principle?

Published on 2024-11-15
Browse:430

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:

    • foo(std::string*) or foo(std::string&)?
  • Passing a tr1::shared_ptr to a function:

    • foo(tr1::shared_ptr* ptr) or foo(tr1::shared_ptr& ptr)?

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:

  • The map keys use references, guaranteeing memory efficiency.
  • The vector pointer allows for dynamic allocation, facilitating vector addition.

Rule of Thumb

Ultimately, the appropriate choice depends on the specific requirements. As a guiding principle, consider:

  • Use references: For efficient memory usage and when you have guaranteed access to the referenced object.
  • Use pointers: When handling nullptrs, working with dynamic memory, or when you need to modify references themselves.
Latest tutorial More>

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