Reputation: 4273
Lets say that I have the following class:
class BigClass
{
public:
BigClass();
~BigClass();
private:
... // many variables
};
And another class:
class SmallClass
{
public:
SmallClass();
~SmallClass();
private:
const BigClass &ref;
};
Notice that I have a reference to a BigClass
object called ref
.
BigClass
object gets out of scope ? Will it be deleted or will it stay alive because of the ref
reference to it ? If it gets deleted, then a good way to do keep it alive would be to have a shared_ptr
instead of a reference ?Upvotes: 1
Views: 203
Reputation: 54325
Is that a good design ? Is there a better way to do that ?
If SmallClass is guaranteed to have a shorter lifetime than BigClass then it is perfectly fine. This kind of thing is often seen in small classes used as "functors."
Otherwise use a smart pointer: unique or shared. Or weak shared.
What is gonna happen when the actual BigClass object gets out of scope ?
If SmallClass still exists and has the reference, it is now an invalid reference and your program will have undefined behavior. That's bad. It probably won't crash but using the reference will write over another object or corrupt the heap's free memory tracking, or overwrite stack values including possibly the function return address.
Will it be deleted or will it stay alive because of the ref reference to it ?
This is not Java. It will be deleted. If you need to track reference counts then you need a shared smart pointer.
If it gets deleted, then a good way to do keep it alive would be to have a shared_ptr instead of a reference ?
Yes.
Upvotes: 3