4

In the below code the variable a is passed to a constructor by reference, received by the parameter x. Then x is passed as a reference to an attribute. The attribute is then initialized with value 3. The program outputs the value 3 when running.

MY QUESTION

Shouldn't the program crash or show 2 because after the constructor is called x should go out of scope and be released and its address should be freed right. and trying to write to it should give a memory access violation. However in this case the x is still in program control holding the address of 'a'

Is this valid c++ behavior or am i missing something?

#include <iostream>
#include <conio.h>

using namespace std;

class myclass {

public:
    int& attribute;
    myclass(int& x):attribute(x) {

    }

    void func() {
        attribute = 3;
    }
};

int main() {
    int a = 2;
    myclass obj(a);
    obj.func();
    std::cout << a;
    _getch();
}
JaMiT
  • 14,422
  • 4
  • 15
  • 31
  • 4
    Initializing a reference from another reference is the same as initializing it from the referred object. A reference is an alias for the referred object in pretty much every sense. Here, `x` *is* `a`. – François Andrieux Aug 22 '19 at 19:30
  • 2
    Reference members in a class is, more often than not, a code smell - and usually a bug. – Jesper Juhl Aug 22 '19 at 19:32
  • 1
    "Shouldn't the program crash" -- You think very highly of Undefined Behavior :-) _Anything_ can happen when you screw up in C++. – alter_igel Aug 22 '19 at 19:48
  • Possible duplicate of [Pass a reference to a reference](https://stackoverflow.com/questions/18473496/pass-a-reference-to-a-reference) – JaMiT Aug 22 '19 at 21:07

2 Answers2

5

No this program is fine. attribute is a reference to a. The fact that x has gone out of scope is neither here nor there.

If you changed your code to

myclass(int x):attribute(x)

then that would be a problem.

john
  • 85,011
  • 4
  • 57
  • 81
3

The behavior of the program line by line

variable "a" is initialized with value 2

int a = 2;  

Initialize obj with the variable a

myclass obj(a);  

First x becomes the reference to a, then attribute becomes the reference to x. Consequently, attribute becomes the reference to a, which has the value 2 at the moment.

myclass(int& x):attribute(x) {}  

Call func() of obj

obj.func();

attribute is the reference to a. Both "attribute" and "a" are changed to 3. Consider them as the same, single variable, just with difference alias. That means, at this moment, attribute and a refers to the same variable, and can be used interchangeably.

void func() {
    attribute = 3;  
}
hehaoqian
  • 166
  • 6