C++ style guide: Difference between revisions

Jump to navigation Jump to search
816 bytes added ,  24 August 2021
→‎references: Add examples
(→‎references: Add examples)
Line 178: Line 178:
=== references ===
=== references ===


Use references when passing variables that will be changed to subroutines rather
Use references when passing variables that will be changed to subroutines rather than the C-style method of passing pointers.
than the C-style method of passing pointers.


When passing variables that are large, but will not be changed in a subroutine (read-only)
{| class="wikitable"
, consider using 'const' references.  This helps avoid overflowing the finite stack capacity
! style="color:green;" | good
of a program while still ensuring that read-only access is enforced.
! style="color:darkred;" | bad
|-
| <syntaxhighlight lang="c++">
void foo (int& a_ref)
{
  // foo changes content of `a_ref`
}
 
void bar ()
{
  int a = 42;
  foo (a);
}
</syntaxhighlight>
| <syntaxhighlight lang="c++">
void foo (int *a_ptr)
{
  // foo changes content of `a_ptr`
}
 
void bar ()
{
  int a = 42;
  foo (&a);
}
</syntaxhighlight>
|}
 
When passing variables that are large, but will not be changed in a subroutine (read-only), consider using 'const' references.  This helps avoid overflowing the finite stack capacity of a program while still ensuring that read-only access is enforced.
 
{| class="wikitable"
! style="color:green;" | good
! style="color:darkred;" | bad
|-
| <syntaxhighlight lang="c++">
void foo (const int& a_ref)
{
  // foo does not change content of `a_ref`
}
 
void bar ()
{
  int a = 42;
  foo (a);
}
</syntaxhighlight>
| <syntaxhighlight lang="c++">
void foo (int& a_ref)
{
  // foo does not change content of `a_ref`
}
 
void bar ()
{
  int a = 42;
  foo (a);
}
</syntaxhighlight>
|}


=== std::string ===
=== std::string ===

Navigation menu