How to initialize an object reference in C ++?

I tried to do

MyClass& x;
x = MyClass(a,b,c);

But C ++ will not let me do this because it believes that x is not initialized at the beginning.

So I tried to do

MyClass& x = MyClass(a,b,c);

But an error occurred, saying invalid initialization of non-const reference of type 'MyClass&' from an rvalue of type 'MyClass'

What about him? It seems I just can’t do anything now. How do I solve the initialization problem?

+4
source share
2 answers

The link must reference an existing object. Therefore, before you can access it, you must first create an object.

MyClass y = MyClass(a,b,c);
MyClass &x = y;
+6
source

A regular reference to constshould not be initialized with an lvalue expression (essentially an expression that refers to a memory location), for example

MyClass o{ a, b, c };
MyClass& r = o;

const, rvalue ( &&), rvalue, , :

MyClass const& rc = foo();
MyClass&& rr = foo();

.

, , , , .. , .

, , .

+9

Source: https://habr.com/ru/post/1649664/


All Articles