Comparison of Virtual Function Pointers in C++

邮差的信 提交于 2019-12-13 13:26:45

问题


Say I want to check to see whether a subclass has implemented one of it's parent's virtual functions (never mind whether this smells of bad architecture... it's an exercise). If I wanted to see if two regular functions were identical, I could just check &f == &g.

// Plain old functions
void f() {}
void g() {}

...

std::cout << "&f " << &f << "\n";               // "1"  OK, for some reason func ptrs are converted
std::cout << "&g " << &f << "\n";               // "1"  to booleans when printed. I can dig it.
std::cout << "&f == &g " << (&f == &g) << "\n"; // "0"  Good, &f and &g are unequal as expected.

But with virtual member functions, behavior is different.

// Base class with a virtual
struct A {
    virtual void f() {}
};

// Subclass which implements f
struct B : public A {
    void f() {}
};

// Subclass which doesn't implement f
struct C : public A {};

...

std::cout << "&A::f " << &A::f << "\n"; // "1"
std::cout << "&B::f " << &B::f << "\n"; // "1"
std::cout << "&C::f " << &C::f << "\n"; // "1" ... okay ... annoying, but alright.

std::cout << "&A::f == &B::f " << (&A::f == &B::f) << "\n"; // "1" DANGER - why does &A::f == &B::f if &f != &g?
std::cout << "&A::f == &C::f " << (&A::f == &C::f) << "\n"; // "1"
std::cout << "&B::f == &C::f " << (&B::f == &C::f) << "\n"; // "1"

std::cout << "(void*)&A::f " << (void*)&A::f << "\n";   // "0x4084b0" Here's what I was actually looking for.
std::cout << "(void*)&B::f " << (void*)&B::f << "\n";   // "0x4084bc" Good - the B::f differs from A::f as it should
std::cout << "(void*)&C::f " << (void*)&C::f << "\n";   // "0x4084b0" Perfect.

std::cout << "(void*)&A::f == (void*)&B::f " << ((void*)&A::f == (void*)&B::f) << "\n"; // "0"
std::cout << "(void*)&A::f == (void*)&C::f " << ((void*)&A::f == (void*)&C::f) << "\n"; // "1"
std::cout << "(void*)&B::f == (void*)&C::f " << ((void*)&B::f == (void*)&C::f) << "\n"; // "0" These are the comparison results I want

So my question is marked by DANGER in the code above. Why does &A::f == &B::f if &f != &g? Is there a way to do the comparison I want without casting to void* (which gives off noisy compiler warnings thanks to -Wpmf-conversions)?

来源:https://stackoverflow.com/questions/33812896/comparison-of-virtual-function-pointers-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!