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
Release: 2024-11-02 20:34:03
Original
409 people have browsed it

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();
}
Copy after login

and

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template