I am fooling around with C++ and const references and am confused why this code works:
#include <iostream>
class A {
public:
A() : a_(50) {}
const int& getA() const { return a_; }
private:
const int a_;
};
int main(int argc, char* argv[])
{
A* a = new A();
const int& var = a->getA();
std::cout << var << std::endl;
delete a;
std::cout << var << std::endl;
}
Result:
50
50
Here are my thoughts:
var stores a reference to a_.
when a is deleted, a_ should also be deleted.
when var is accessed again, it no longer contains a valid reference and a segmentation fault should occur.
Why does this work? I do not believe I make a temporary copy.