I tried to do
MyClass& x;
x = MyClass(a,b,c);
But C++ won't let me do so because it thinks that x is uninitialized at the beginning.
So I tried to do
MyClass& x = MyClass(a,b,c);
But got error saying invalid initialization of non-const reference of type 'MyClass&' from an rvalue of type 'MyClass'
What's wrong with it? It seems that I simply can't do anything now. How do I get around the initialization issue?
An ordinary reference to non-const
must be initialized with an lvalue expression (essentially an expression that refers to a memory location), e.g.
MyClass o{ a, b, c };
MyClass& r = o;
If the reference is to const
, or if it is an rvalue reference (denoted by &&
), then the initializer can instead be an rvalue expression, such as a temporary produced by a function invocation:
MyClass const& rc = foo();
MyClass&& rr = foo();
In these cases, for a local reference the lifetime of the temporary is extended to the scope of the reference.
And one special feature is that if the initializer produces a temporary of a derived class, it's that full derived class object whose lifetime is extended, i.e. there's no slicing to the class specified for the reference.
More generally the reference can be bound to any part of a temporary, as long as that part has a compatible type, and this will extend the lifetime of the full temporary object.
A reference must refer to an already-existing object. So you need to have an object first before you can refer to it.
MyClass y = MyClass(a,b,c);
MyClass &x = y;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With