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?
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.
Yes, it does.
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.