Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen to use references vs. pointers
    primarykey
    data
    text
    <p>I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an API?</p> <p>Naturally some situations need one or the other (<code>operator++</code> needs a reference argument), but in general I'm finding I prefer to use pointers (and const pointers) as the syntax is clear that the variables are being passed destructively.</p> <p>E.g. in the following code:</p> <pre><code>void add_one(int&amp; n) { n += 1; } void add_one(int* const n) { *n += 1; } int main() { int a = 0; add_one(a); // Not clear that a may be modified add_one(&amp;a); // 'a' is clearly being passed destructively } </code></pre> <p>With the pointer, it's always (more) obvious what's going on, so for APIs and the like where clarity is a big concern are pointers not more appropriate than references? Does that mean references should only be used when necessary (e.g. <code>operator++</code>)? Are there any performance concerns with one or the other?</p> <p>EDIT (OUTDATED):</p> <p>Besides allowing NULL values and dealing with raw arrays, it seems the choice comes down to personal preference. I've accepted the answer below that references <a href="https://google.github.io/styleguide/cppguide.html#Reference_Arguments" rel="noreferrer">Google's C++ Style Guide</a>, as they present the view that "References can be confusing, as they have value syntax but pointer semantics.".</p> <p>Due to the additional work required to sanitise pointer arguments that should not be NULL (e.g. <code>add_one(0)</code> will call the pointer version and break during runtime), it makes sense from a maintainability perspective to use references where an object MUST be present, though it is a shame to lose the syntactic clarity.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload