Sign in to follow this  
mongrol

C++ references and object lifetimes

Recommended Posts

Hi folks, A quick question on references and object lifetimes. I have one class that creates another then passes a reference to another object.
class Creature()
{
    Weapon weapon;
    Gameworld.addWeapon(weapon&);
}
If the Creature object is destroyed is the object it created also destroyed and the reference passed to GameWork is then invalid? I realise if I passed a pointer it would then be invalid and left hanging but what about references?

Share this post


Link to post
Share on other sites
Quote:
Original post by mongrol
Hi folks,
A quick question on references and object lifetimes.

I have one class that creates another then passes a reference to another object.


class Creature()
{
Weapon weapon;
Gameworld.addWeapon(weapon&);
}


If the Creature object is destroyed is the object it created also destroyed and the reference passed to GameWork is then invalid?

I realise if I passed a pointer it would then be invalid and left hanging but what about references?
Yes, references can become invalid under certain circumstances.

The exact scenario you have in mind isn't very clear though (for one thing, the bit of code you posted isn't valid C++). Can you possibly post an actual code example that demonstrates what you have in mind?

Share this post


Link to post
Share on other sites
References work internally the same way as pointers. So they get invalid under the same circumstances.

Basically, references are "const pointer that are always initialized and never 0."

Ciao, Imi.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this