1

This example was taken from §8.5.3/5 (first bullet point) in the C++11 Standard:

struct A { };
struct B : A { operator int&(); } b;
int& ri = B();

If it does, is there any way to access the temporary B(), in the code below?

#include <iostream>

struct A { };
struct B : A { int i; B(): i(10) {} operator int&() { return i; } } b;

int main()
{
    int& ri = B();
    std::cout << ri << '\n';
}
Wake up Brazil
  • 3,421
  • 12
  • 19
  • As far as I know, you can't; I don't know if the standard specifies anything, though. – kirbyfan64sos Jun 21 '14 at 19:08
  • 2
    it's not extended. (How should the compiler know, in the general case anyway, that `operator int&` returns part of its object instead of something unrelated? – Deduplicator Jun 21 '14 at 19:11
  • @chris The Standard says this is valid: `int& ri = B();` and it seems to me the object B() is kept on the stack, as `ri` is a reference to its member `i`. – Wake up Brazil Jun 21 '14 at 19:16
  • @WakeupBrazil, Shoot, I missed the `operator int &`, sorry. – chris Jun 21 '14 at 19:21

1 Answers1

3

No, the destructor for the temporary B object runs at the end of the full expression, as usual. It is not bound to any reference.

In your second example, ri is a reference to an int object whose lifetime has ended.

Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • "ri is a reference to an int object whose lifetime has ended". How come I can print `ri` in the code. `ri` definitly is not a dangling reference. – Wake up Brazil Jun 21 '14 at 19:22
  • 1
    @WakeupBrazil, Printing a dangling reference is undefined behaviour. It can "work" or do anything else. But it can't work. – chris Jun 21 '14 at 19:23
  • @WakeupBrazil You can print `ri` because of http://stackoverflow.com/a/6445794/273767 – Cubbi Jun 21 '14 at 19:23
  • @chris But the example in the Standard doesn't say anything about a dangling reference or UB in this case. – Wake up Brazil Jun 21 '14 at 19:24
  • @WakeupBrazil, It doesn't need to in order for either to be true. The standard's example doesn't have any UB. The reference isn't being used, and even if it was, the implementation of `operator int &` could return a reference to a global variable or something. – chris Jun 21 '14 at 19:25
  • @WakeupBrazil [This](http://coliru.stacked-crooked.com/a/0be904a9bb6affd8) should make it clear your example has UB. The example in the standard is meant to illustrate how an `int&` can be bound to a seemingly unrelated instance of type `B` because of the existence of the conversion operator. The example by itself is fine. – Praetorian Jun 21 '14 at 19:27