没有虚拟继承的奇怪行为

时间:2017-12-21 15:35:20

标签: c++ c++11 inheritance virtual-inheritance

我正在编写一段代码,它表现出非常奇怪的行为。我设法在一个简单的hello世界风格程序中复制它,下面是代码:

#include <iostream>
using namespace std;

class Test
{
public:
    virtual ~Test() = default;

protected:
    virtual void SetUp() { }
};

class ICallbackReceiver
{
public:
    virtual ~ICallbackReceiver() = default;
    virtual void onReady() = 0;
};

// C-style callback
void readyReceiver(void* userdata)
{
    cout << "3) readyReceiver\n";
    static_cast<ICallbackReceiver*>(userdata)->onReady();
}

using callback_t = void(*)(void*);
callback_t myCallback;
void* myUserData;

void registerCallback(callback_t callback, void* userData)
{
    cout << "2) registerCallback\n";
    myCallback = callback;
    myUserData = userData;
}

class ConfigurableTest : public /*virtual*/ Test, public ICallbackReceiver
{
public:

    void SetUp() override
    {
        cout << "1) ConfigurableTest::SetUp\n";
        registerCallback(&readyReceiver, static_cast<void*>(this));
    }

    void onReady() override
    {
        cout << "4) ConfigurableTest::onReady\n";
    }
};

int main()
{
    ConfigurableTest test;
    test.SetUp();

    myCallback(myUserData);

    return 0;
}

每当调用myCallback时,必须测试某些内容。这是应该显示的输出:

1) ConfigurableTest::SetUp
2) registerCallback
3) readyReceiver
4) ConfigurableTest::onReady

但是,除非我为virtual类指定Test继承,否则这是我看到的输出:

1) ConfigurableTest::SetUp
2) registerCallback
3) readyReceiver
1) ConfigurableTest::SetUp
2) registerCallback

正如您所见,ConfigurableTest::onReady永远不会被调用,但ConfigurableTest::SetUp实际上被调用了两次!

这种行为的起源是什么?如何在不使用virtual继承的情况下重新生成代码以重现正确的行为?

1 个答案:

答案 0 :(得分:4)

问题是因为您进行了转化ConfigurableTest - &gt; void * - &gt; ICallbackReceiver,不允许的。您需要从ConfigurableTest转换回相同的类型void * - 在这种情况下没有错误。

另见multiple inheritance: unexpected result after cast from void * to 2nd base class