I am reading a book and the author has a noncopyable class which ends up as a member variable of another class. It stuck out to me, because of the way the author did it and because he preferred a pointer to a reference. Let me give an example.
1 2 3 4 5 6 7 8 9 10
class Integer; // noncopyable
class WrapperInteger
{
public:
explicit WrapperInteger(Integer& x)
: mInteger(&x)
{}
Integer* mInteger;
};
What the author did that surprised me was he passed the Integer object by reference and then he takes the address of the object and contructs mInteger pointer. Why start with a reference to end with a pointer?
1 2 3 4 5 6 7 8 9 10 11
class Integer; // noncopyable
class WrapperInteger
{
public:
explicit WrapperInteger(Integer* x)
: mInteger(x)
{}
Integer* mInteger;
};
If I wanted a pointer this seems more straightforward (and identical). I do understand this may just be preference.
1 2 3 4 5 6 7 8 9 10
class Integer; // noncopyable
class WrapperInteger
{
public:
explicit WrapperInteger(Integer& x)
: mInteger(x)
{}
Integer& mInteger;
};
Further, I've read to prefer references to pointers, so why not this?
Are all these examples accomplishing the same task? Also, why might the author prefer a pointer over a reference? Finally, is there a name for this usage?
The basic idea is to have a wrapper that can be used like a reference. While a normal reference will always refer to the same object, a wrapped reference simulates a reference that can be rebound to refer to a different object. To simulate a copyable, assignable wrapper, internally a non-null pointer is held; pointers are copyable and assignable.