2

I have this example:

  #include<iostream>
  using namespace std;

  struct Foo
  {
      int const& rci; 
      Foo(int const& x) : rci(x){}
  };

  int main()
  {
      Foo f(7);
      cout << f.rci << endl;
  
  }

I've tried this code on many compilers and it works fine printing 7 because the reference member is bound to a temporary but running it on the application decoder it gives me value 0 rather than 7.

Is this a problem in the application Decoder or in my code?

Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 1
    Probably works with an integer literal because the compiler may place the literal into effectively a static variable. For all intents and purposes, though, you've got a dangling reference. – AndyG Dec 29 '20 at 15:55
  • 1
    compiling with `g++ -O -Wall` (or O1/O2/...) produces `warning: ‘’ is used uninitialized in this function [-Wuninitialized]` and prints 0. Without optimization no warning and prints 7. The problem is not *Decoder* but your source code – bruno Dec 29 '20 at 16:03
  • 1
    @AndyG You are correct. – Adrian Mole Dec 29 '20 at 16:05
  • 2
    The life of the `7` ends right after `Foo f(7);`. Then `f.rci` becomes a dangling reference. Try with ASAN ([`-fsanitize=address`](https://gcc.godbolt.org/z/bKbz6o)): `ERROR: AddressSanitizer: stack-use-after-scope` – rustyx Dec 29 '20 at 16:15

0 Answers0