130

Why can you do this

int a;
const double &m = a;

But when you do this

int a;
double &m = a;

you get an error?

error: non-const lvalue reference to type 'double' cannot bind to a value of unrelated type 'int'

Edit:

To be more specific I am trying to understand the reason non-const references can't bind temp objects.

2
  • 6
    This question can be interpreted in one of two ways: either you need to know that there is a rule that allows const references binding to temporary values, or you want to know the rationale of why. You'll probably get both kinds of answers, but you are likely interested in only one of them... which is it?
    – DanielKO
    Commented Sep 2, 2013 at 3:17
  • 1
    Error message here is a bit confusing. I would expect some thing like - error: invalid initialization of non-const reference of type ‘double&’ from an rvalue of type ‘double’.
    – Mahesh
    Commented Sep 2, 2013 at 3:30

4 Answers 4

108

That is because a temporary can not bind to a non-const reference.

double &m = a;

a is of type int and is being converted to double. So a temporary is created. Same is the case for user-defined types as well.

Foo &obj = Foo(); // You will see the same error message.

But in Visual Studio, it works fine because of a compiler extension enabled by default. But GCC will complain.

5
  • 29
    I downvote because you are missing solution. Just write one sentece more and all problems gone. What would you do in "Foo &obj = Foo();" case ? Commented Dec 30, 2019 at 16:01
  • 7
    @AbbasPerçin the solution is kind of already given in the question: Just make it a constant: const Foo &obj = Foo();
    – Jwf
    Commented Dec 22, 2020 at 12:01
  • 6
    @AbbasPerçin the question was why and not how, so I think there is nothing wrong with this answer.
    – tzman
    Commented Oct 14, 2021 at 14:37
  • What if I want to modify obj later? Do I just do Foo obj = Foo(); obj.set_name("name"); ?
    – CSY
    Commented Aug 18, 2023 at 22:00
  • Thanks. I had missed that a temporary was being created in auto& sqrtd = static_cast<double(*)(double)>(std::sqrt);. I see now I have the same problem as above. I knew adding const would remove the error, and now I know why. Commented Apr 25 at 11:33
48

Because making modification on a temporary is meaningless, C++ doesn't want you to bind non-const reference to a temporary. For example:

int a;
double &m = a;  // caution:this does not work.

What if it works?
a is of type int and is being converted to double. So a temporary is created.

You can modify m, which is bound to a temporary, but almost nothing happens. After the modification, variable a does not change (what's worse? You might think a has changed, which may cause problems).

5
  • 2
    But what if the temporary contains a pointer to some other resource? Then making modification on a temporary is not meaningless.
    – Enzo
    Commented Dec 17, 2018 at 10:14
  • @Enzo it not looks like a good practice. Or you can show a good example here?
    – xinnjie
    Commented Dec 29, 2018 at 1:42
  • 1
    @Enzo if the temporary object contain pointer to other resource, it should be handled with move constructor. Temp object will be deleted anyway so I think you shouldn't do anything important with it. Commented Jul 8, 2019 at 2:26
  • @xinnjie, allowing mutable temporaries could be useful in some cases. For example write_data_to ( Writeable_File ( "/some/path" ) ); It this case, there is a persistent side-effect that outlives the temporary Writeable_File object. I can think of other examples that involve filtering or adapting input to or output from some algorithm. I can think of other examples that involve encapsulating levels of mutable state inside some algorithm. For example, a parser could pull input from a temporary lexer. However, for better or for worse, C++ does not support passing mutable temporaries.
    – mpb
    Commented May 4, 2020 at 18:02
  • @mpb mutable temporaries make peaple easy to make mistake. As for your example, move setantic maybe helpful? Something like write_data_to ( Writeable_File&& ) ),lifecircle of varibale is more clear. But after all, I agree with you, supporting passing mutable temporaries is convinient in some usages.
    – xinnjie
    Commented May 7, 2020 at 9:22
1

Simple explanation with example

Once a referenced is set to object / variable,it cannot be modified to refer to another object

    int a = 1;      //this are variable
    int b = 2;
    
    int &ref1 = a;
    int &ref1 = b; // this is error
    ref1 = b;      // now a = 2
1

A temporary lives, as the name suggests, only briefly. It is normally destroyed at the end of the expression of which it is a part, that is, at the next semicolon or, rarer, at the end of the controlling expression in if statements etc.

There is a single way to extend the temporary's life: By binding it to a const ref (a normal ref won't do the job.).

Therefore, the formal reason why you cannot bind temporaries to non-const refs is:

Because the reference would be immediately dangling.

Now you may ask "why do non-const refs not extend a temporary's life as well?" The design decision was probably made because it would be too error-prone. Even extending the lifetime through a const ref is error-prone: People may return that reference and use it to initialize another one which will be dangling since the original reference's scope was left. With a non-const ref, people might additionally think that writing through the reference would have an effect, for example, when it usually doesn't. Of course one could use the non-const ref like any local variable: Changes made through it will only be visible through it, and short of copying the referenced object there is no way to access it outside the ref's scope. But for that use case we have a true and tested zero-overhead solution which everybody understands immediately: Local variables ;-).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.