Question

Suppose I have a C++ class with an attribute that is a reference:

class ClassB {
    ClassA &ref;
public:
    ClassB(ClassA &_ref);
}

Of course, the constructor is defined this way:

ClassB::ClassB(ClassA &_ref) : ref(_ref) { /* ... */ }

My question is: When an instance of class 'ClassB' is destroyed, is the object referenced by 'ClassB::ref' also destroyed?

Was it helpful?

Solution

A reference is nothing but an alias for a variable, the alias gets destructed, not the actual variable. You could consider it some kind of pointer, but there are reasons to refrain from this kind of (evil) thoughts :).

OTHER TIPS

No. Reference members do not affect the lifetime of whatever they point to. This means the thing they alias may have a longer or a shorter lifetime than that of the reference.

On the other hand, const references can affect the lifetime of what they point to if they point to a temporary.

In your case it does not.

No. That's why you need a ~ClassB destructor if ClassB is responsible for the storage of ref which it might not be.

When an object is eliminated in C++, its memory is deallocated and thus everything that was embedded in it (such as member variables) is lost as well.

In the case of a pointer, the pointer is a member variable that contains an address, so the address is "destroyed" but the referenced object, if any, is not.

In the case of a reference member, the address is destroyed, but the target is not affected.

A class may define a destructor that could define special behaviors. One common such behavior is to invoke cleanup operations on members (if any), and to deallocate memory that was dynamically allocated earlier. Here, however, you already got an object so you should not be the one deallocating it.

No; references are merely an alternate syntax for pointers. The value they reference won't be modified if the reference is deallocated.

If you want it to be destroyed, you will have to encapsulate it (normally done via "smart" pointers, like std::shared_ptr or std::unique_ptr), that will automatically release the memory in an appropriate fashion on destruction of B. In-language references have no memory freeing behaviour associated with them, except the actual memory of the reference itself, as opposed to the referred.

You will have to build and understand your own memory model. People typically use shared_ptr and reference counting for basic uses.

I don't have the C++ spec on hand, but my guess is "No".

Pointers aren't deleted automatically when an object is destroyed, I see no reason that a reference should be different. Plus, having the reference automatically destroyed would be ripe for interesting bugs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top