Home >Backend Development >C++ >Pointers vs. References: When to Use Each in Function Parameters?

Pointers vs. References: When to Use Each in Function Parameters?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 20:34:03433browse

Pointers vs. References: When to Use Each in Function Parameters?

Pointers vs. References in Parameter Passing

Regarding pointers and references as function parameters, the code snippets provided do have functional similarities:

int foo(bar* p) {
  return p->someInt();
}

and

int foo(bar& r) {
  return r.someInt();
}

However, there are subtle differences between the two:

  • Null Pointers: The pointer parameter allows for passing nullptr, while the reference parameter cannot be assigned nullptr.
  • Optimizations: In certain cases, the compiler may optimize reference parameters over pointers, reducing overhead.

In C , references intentionally are not implemented explicitly with pointers. Instead, they serve as "synonyms" for the referenced variable. This concept enables compiler optimizations where pointers would be unnecessary.

Other notable differences between pointers and references include:

  • Cannot Reassign: References cannot be reassigned, while pointers can.
  • Address: Taking the address of a pointer returns the address of the pointer itself, while taking the address of a reference returns the address of the referenced object.

The above is the detailed content of Pointers vs. References: When to Use Each in Function Parameters?. 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