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.

2
  • Have you tried to compile the code? What did you notice? Commented Mar 19, 2020 at 21:06
  • a and b are exactly the same except for the result of decltype(x) Commented Mar 19, 2020 at 23:30

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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- The lifetime of the both temporary objects is as long as the lifetime of references thet refer these temporary objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.