What happens to a reference variable when its reference 'dies'?

322 views Asked by At

Let's say I create a class called MyClass which contains a reference variable m_my_resource. This reference variable is essentially just a named alias associated with some other memory location.

MyClass

class MyClass
{
    public:    
        MyClass(const MyResource& my_resource) :
            m_my_resource(my_resource){}

    private:
        const MyResource& m_my_resource;
}

Now lets say I try to do the following:

main
{
    MyClass my_class(utils::getMyResource());

    //continue doing stuff
}

What exactly happens in this scenario? I have defined MyClass to only have a single constructor which takes in a reference (lvalue reference) to MyResource.

However, within my main function, I construct an instance of MyClass with a temporary object (rvalue). Why is my code able to compile? Doesn't my_class now contain a reference variable that is associated with some temporary memory location? Essentially the variable in which the reference variable was associated with has now 'died', what happens to the reference variable?

Furthermore, is this a case where I would want my class to have a constructor that accepts rvalue references?

2

There are 2 answers

0
Sam Varshavchik On BEST ANSWER

Why is my code able to compile?

Just because your code compiles, doesn't mean that it will work correctly. Otherwise, every program in the world will be automatically bug-free, by the virtue of it successfully passing the compilation phase, and there wouldn't be any need for anyone to learn how to use a debugger.

Obviously, things don't work this way.

Doesn't my_class now contain a reference variable that is associated with some temporary memory location?

Yes, it does.

Essentially the variable in which the reference variable was associated with has now 'died', what happens to the reference variable?

Nothing happens to your reference variable. It still exists. But referencing the object -- by that it means attempting to invoke its methods or access its members -- results in undefined behavior.

0
Saxon On

If getMyResource() returns a MyResource object, somewhere in getMyresource() you are allocating memory for the object (on the heap may be), so you have to release the allocated memory. For instance call the MyResource destructor for m_my_resource in the MyClass destructor. If you don't you are going to have memory leaks on your program. In C++ there is no garbage collector to release automatically allocated memory, you have to do it by yourself, but there is non apparent problem compiling, just executing, if memory leaks are a matter.