Home
ObjexxFCL 4.2
 

Reference

Reference is a class template providing the semantics of Fortran's POINTER, acting as a re-attachable C++ reference:

int i( 42 );
...
Reference< int > r( i ); // r is a reference to i
// r.attached() is true
// r.attached( i ) is true
// r.associated() is true
// r.associated( i ) is true
r = 53; // Now r == i == 53
...
r.detach(); // Disassociate r
// r.attached() is false
// r.associated() is false
...
int j( 33 );
r.attach( j ); // Now r is a reference to j
...
r >>= i; // Reattach to i using operator >>= syntax

References can also allocate their own arrays:

Reference< Array2D_int > r; // Unattached reference to a 2D array
r.allocate( 3, 3 ); // r creates and refers to a 3x3 array
...
r.deallocate(); // r is unattached again

Notes on Reference usage:

  • The Type can be const-qualified.
  • References can automatically convert to the contained object.
  • Explicit conversion to the contained object is available with the syntax reference().
  • For dot and function call usage the explicit syntax is needed, such as reference().method() or reference()( arg ).
  • Typedefs for common types are provided, such as Reference_int for Reference< int >.
  • References that are directly allocated create their own arrays and breaking any association to other arrays. To emulate Fortran POINTERs, References do not automatically delete the allocated array in their destructors (other References may be referring to them): it is up to the application code to deallocate them when no longer needed or else memory will leak. This makes References, like POINTERs, difficult to use without leaks so their use is discouraged in new code.
  • References to References are supported.
  • While Reference is very useful for code converted from Fortran, more common C++ references and (smart) pointers should be preferred where sufficient for new code.