Given a class "A" exists and is correct. What would be some of the negative results of using a reference to "A" instead of a pointer in a class "B". That is:
// In Declaration File
class A;
class B
{
public:
B();
~B();
private:
A& a;
};
// In Definition File
B::B(): a(* new A())
{}
B::~B()
{
delete &a;
}
Omitted extra code for further correctness of "B", such as the copy constructor and assignment operator, just wanted to demonstrate the concept of the question.
The immediate limitations are that:
A
it refers to, but you cannot reallocate or reassign a
during B
's lifetime.a
must never be 0
.Thus:
B
should not be copy constructible, unless you teach A
and its subtypes to clone properly.B
will not be a good candidate as an element of collections types if stored as value. A vector of B
s would likely be implemented most easily as std::vector<B*>
, which may introduce further complications (or simplifications, depending on your design).These may be good things, depending on your needs.
Caveats:
a
is assignable and assignment is reachable within B
.You can't change the object referred to by a after the fact, e.g. on assignment. Also, it makes your type non-POD (the type given would be non-POD anyway due to the private data member anyway, but in some cases it might matter).
But the main disadvantage is probably it might confuse readers of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With