Home >Backend Development >C++ >When to Pass by Reference or Pointer in C : A Guiding Principle?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 16:31:01777browse

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<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:

  • 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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn