Re: reference member variable question
On May 3, 8:37 pm, Bart Simpson <123evergr...@terrace.com> wrote:
Salt_Peter wrote:
On May 3, 7:35 pm, Bart Simpson <123evergr...@terrace.com> wrote:
If a class has a member variable that is a reference. What happens to
teh class that is being referenced, when the containing class is destroyed?
e.g.
Class A{ };
class A { };
Class B
class B
{
public:
B(const A& a):m_a(a){}
A& m_a ;
};
int main()
{
A a;
B * b = new B(a);
delete b ; // is a deleted also at this point ?
};
No, the instance 'a' dies at the end of the scope its in, namely - the
closing brace of int main() in this case. In other words: an instance
of class B does not 'own' the instance of type A. If you require 'a'
to die with the deallocation of *b, you'ld probably want a member of
type A in class B.
class B
{
A a;
public:
B() : a() {}
B( const A& r_a ) : a( r_a ) {}
};
And nothing stops you from declaring and defining a member reference
to private member 'a'.
Class B contains a reference to class A. since a reference IS the object
itself, I dont understand how come A is not destroyed when B is
destroyed - unless some kind of "reference counting" is employed "under
the hood" ?. BTW this is the desired behaviour - I just dont understand
how or why it works though ... and am seeking more of an insight to
explain this (maybe someone has a copy of the language reference)?
A reference is a permanent alias, its not the target object itself.
An object's lifetime is governed by the scope its in. Regardless of
whether a pointer of reference is targetting it.
Many will argue that a reference is an independant object altogether,
except that it happens to share its target's interface (public member
functions), returns its taget's address but it lives in its own
world / dimension / scope.
It doesn't make sense to have one object and 20 references to it and
then claim that you have 21 objects.
If your name is Bartholomy and you have a reference/alias of Bart -
thats still the same person.
If i chose to remove Bart from my list of friends - that doesn't
delete you. I'ld have to delete Bartholomy to do that.
If i slap Bart accross the face, only one person got slapped -
Bartholomy.