May 20, 2010

C++ Pattern: Use pointer behind a reference

The advantage is in the header file the member variable is forward declared so the user of the class only needs the header file in their class source file (and not in their header) In header file declare the reference object:
namespace aaaa { namespace bbbb {
  class xxxx;
  /// Reference member variable.
 aaaa::bbbb::xxxx& memberVar;
In source file assign reference using *new()
SomeClass::SomeClass(const SomeClass &time)
    // Here is the trick, new() and dereference (*) 
    // immediately into a reference object
  : memberVar(*new xxxx(time.memberVar)) {

SomeClass::~SomeClass() {
  delete &memberVar;

No comments: