Re: Is this a compiler bug?
"Martin Lafferty" <null@null.com> schrieb im Newsbeitrag
news:%23knRrOe5GHA.3404@TK2MSFTNGP03.phx.gbl...
My compiler is VC++ 2005.
Could some wise soul please explain to me why the following code does
not work as I expect it to?
//Begin snippet
#include <iostream>
#include <tchar.h>
template<typename T>
void Test(const char *Name, const T &Func) {
std::cout<<Name<<std::endl;
Func();
}
template<typename T>
struct func {
const T &_a;
func(const T& A): _a(A) {}
void operator()() const {
std::cout<<"a="<<_a<<std::endl;
}
};
struct int_func: func<int> {
int_func(int a): func<int>(a) {}
};
int _tmain(int argc, _TCHAR* argv[]) {
Test("using func", func<int>(42)); //writes 42 to cout
Test("using int_func", int_func(42)); //writes random int to cout
return 0;
}
//End snippet
Of course I could do this with a typedef but the real code is a bit
more complicated than this simple test case.
The temporary 'int_func' object seems to get created correctly, but as
soon as the constant "using int_func" then _a gets corrupted. Any
insights into what is going on here would be much appreciated.
For the first call of Test, what happens basically is
- create a temporary int (A) and set its value to 42
- create a temporary func<int> (B) and pass a reference to A to B's
constructor
- store the reference to A in one of B's members
- call Test(..., B)
- call B.operator()()
- access the value of A through a reference stored in B
- return from Test
- destory B
- destroy A
For the second call to Test, however, you get
- create a temporary int_func (B)
- call B's constructor with 42 as its argument (the argument is a local
variable (A) inside B's constructor)
- call func<int>'s constructor with a reference to A
- save the reference to A
- destroy A
- call Test(..., B)
- call B.operator()()
- access (what?) through the dangling reference stored in B
- return from Test
- destroy B
This is not a compiler bug, but yours. You can fix that problem by changing
int_func's constructor to
int_func(int const& a): func<int>(a) {}
HTH
Heinz