Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize an object reference in C++?

Tags:

c++

reference

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?

like image 381
OneZero Avatar asked Dec 05 '22 17:12

OneZero


2 Answers

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.

like image 56
Cheers and hth. - Alf Avatar answered Jan 05 '23 08:01

Cheers and hth. - Alf


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;
like image 43
artm Avatar answered Jan 05 '23 08:01

artm