这个(示例)代码崩溃,我不明白为什么。编译:gcc 4.8.3
#include <cstdio>
struct virtual_initialisation {
virtual int foo() { return 4711; }
template <typename T>
virtual_initialisation(int (T::*foo)()) {
// This is the crashing statement:
fprintf(stderr, "%i\n", (dynamic_cast<T*>(this)->*foo)());
}
};
struct A : virtual virtual_initialisation{
int foo() { return 23; }
A()
: virtual_initialisation(&A::foo)
{}
};
struct B : A {
int foo() { return 42; }
B()
: virtual_initialisation(&B::foo)
{}
};
int main(int argc, char * argv[]) {
B b;
return 0;
}
使用-O3编译,但-O0产生相同的结果(除了更多的堆栈跟踪条目;)
$ g++ -O3 -g stackoverflow.cpp -o stackoverflow && valgrind ./stackoverflow
==19328== Invalid read of size 8
==19328== at 0x400745: main (oops.cpp:11)
==19328== Address 0x0 is not stack'd, malloc'd or (recently) free'd