In the below code the variable 'a' is passed to the constructor by reference and the reference of the parameter of the constructor receiving the address of a 'x' is passed as reference to attribute.The attribute is then initialized with value 3. The program is outputing 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();
}
Aucun commentaire:
Enregistrer un commentaire