【发布时间】:2012-01-10 15:33:45
【问题描述】:
我想我发现了一个 G++ 错误,但我不确定。我无法解释。编译不应该通过 BAD 代码,但确实如此。 g++-4.5 和 g++4.6 -std=c++0x 通过此代码而没有任何警告。
编译器认为指向 Bar 对象的指针是 Bar 对象本身。 我疯了。我花了很多时间来解决这个错误。有什么技术可以防止这种错误吗?
错误代码给出:
g++-4.6 for_stackoverflow.cpp && ./a.out
address of bar in main() 0xbff18fc0
Foo 0x9e80008 Bar 0xbff18fec
Foo 0x9e80028 Bar 0xbff18fec
Foo 0x9e80048 Bar 0xbff18fec
end
源代码:
#include <iostream>
#include <list>
#include <iomanip>
#include <algorithm>
#define BAD
using namespace std;
class Bar;
class Foo {
public:
virtual void tick(Bar & b) {
cout << "Foo " << this << " Bar " << setw(14) << (&b) << endl;
}
};
class Bar : public list<Foo*> {
};
int main() {
Bar bar;
cout << "address of bar in main() " << &bar << endl;
bar.push_back(new Foo());
bar.push_back(new Foo());
bar.push_back(new Foo());
#ifdef GOOD
for_each(bar.begin(), bar.end(), bind2nd(mem_fun(&Foo::tick), bar));
#elif defined(BAD)
for_each(bar.begin(), bar.end(), bind2nd(mem_fun(&Foo::tick), &bar));
#else
#error "define GOOD xor BAD"
#endif
cout << "end" << endl;
return 0;
}
【问题讨论】: