in the folowing code, the _bla member of both instances of Var seems to represent the same memory location, as setting the value on one instance also changes the other. When executing the program, the output is:
v: 44 v2: 44 x: 22
Can someone please explain?
#include <iostream>
using namespace std;
template<typename T> class Var {
T &_bla;
public:
Var(T t) : _bla(t) {}
int bla() const {
return _bla;
}
};
using namespace std;
int main() {
cout << "Hello, World!" << endl;
int x = 22;
Var<int> v = {x};
Var<int> v2 = {44};
cout << "v: " << v.bla() << " v2: " << v2.bla() << " x: " << x << endl;
return 0;
}
It's undefined behaviour, which means everything is possible.
The parameter t of ctor is passed by value, it will be copied from the argument and then assigned to _bla by reference, and when get out of the scope of ctor, the parameter t is deallocated, now the member variable _bla become dangled reference.
You may reconsider your design, do you need the member variable to be a reference? And what should be the type of parameter t? By const reference, by reference, by value? (In your case, it's obviously wrong to pass it by value.) It's better to consider carefully when you use reference for member variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With