Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ pass by reference tricky situation

I’m trying to figure what happens to an "rvalue",temporary object, after the variable used to refer this object deleted from stack.

Code example:

#include<iostream>
using namespace std;

class Base
{
  private:
  int &ref;
  public:
  Base(int &passed):ref(passed)
  {
    cout << "Value is " << ref << endl;
  }
  int getvalue(){
    return ref;
  }
};

int main()
{
  Base *myobject;
    {
    int ref=10;
    myobject = new Base (ref);
    ref++;
    }                           //ref delete from stack. 
  cout << myobject->getvalue() << endl;
  return 0;
}

I expected the second output(second cout) to give me some random garbage because ref deleted but instead I got the value of the current state of ref, I wander what happened after the ref got deleted is it pure luck? or myobject.ref stored the value of the ref he construct with?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Edit: adding a visualizer to support my point that in the end myobject.ref pointing nowhere C++ visualizer

>Solution :

is it pure luck?

Yes. The lifetime of the object to which the reference refers ends at the } after ref++;.

Trying to read the value of the object after that causes undefined behavior. Undefined behavior means that you have no guarantee how the program will behave, which includes the possibility of it seemingly working, but another run or compilation of the program may give you a different result.

Practically speaking, destroying a int object doesn’t require the execution of any machine instructions and if the object has space allocated on the function’s stack, there is a good possibility that the value will just be read from the location where the int object was located, with whatever value it had last. The compiler does not need to overwrite it.

But you can see undefined behavior in action if you compile with optimizations enabled. For example GCC 11.2 with -O2 on x86_64 produces the output

Value is 10
10

but without optimization flags it produces

Value is 10
11

(see https://godbolt.org/z/EqKG83c18).

But undefined behavior doesn’t just mean that the value printed will be unspecified. The whole program has no behavior guarantees and it could also output nothing or garbage text or anything else.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading