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?