1
const T   a {}; // constant of type T
const T&  b {}; // ???
      T   c {}; // variable of type T
      T&  d {}; // error

What is the difference between a and b?
b is a reference but I don't assign a object to it: in that instruction I initialize it by T constructor.
The address of b is between the addresses of a and c, so it seems the b and a have no differences.

And if I can declare and initialize b why d gives compilation error?

I talked about a generic type T. I tested the code above either for primitive types and classes and the results are the same.

DPD-
  • 412
  • 1
  • 5
  • 15

1 Answers1

2

In these declarations

const T   a {}; // constant of type T
const T&  b {}; 

there is created constant object a that is default initialized and constant reference b to temporary object that is default initialized.

The compiler issues an error for this declaration of a reference

T&  d {}; // error

because there is declared a non-constant reference to a temporary object.

You could declare an rvalue reference the following way

T&& d {};

Here is a demonstrative program

#include <iostream>

int main() 
{
    const int &ri {};

    std::cout << "ri = " << ri << '\n';

    int && rri {};

    std::cout << "rri = " << rri << '\n';

    return 0;
}

The program output is

ri = 0
rri = 0
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • So I guess that in `b` the lifetime of the temporary object is extended and then to "correct" `d` I would have to use an rvalue reference: ```T&& d {};``` Right? – DPD- Mar 19 '20 at 21:26
  • 1
    @DPD- The lifetime of the both temporary objects is as long as the lifetime of references thet refer these temporary objects. – Vlad from Moscow Mar 19 '20 at 21:31