本文介绍了为什么(成员)函数指针在Visual C ++中表现如此奇怪?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常奇怪的问题,我已经减少到以下测试用例:

I've had a really bizarre problem that I've reduced to the following test case:

#include <iostream>
#include <map>
#include <string>

struct Test
{
    std::map<std::string, void (Test::*)()> m;
    Test()
    {
        this->m["test1"] = &Test::test1;
        this->m["test2"] = &Test::test2;
    }
    void test1() { }
    void test2() { }
    void dispatch(std::string s)
    {
        if (this->m.at(s) == &Test::test1)
        { std::cout << "test1 will be called..." << std::endl; }
        else if (this->m.at(s) == &Test::test2)
        { std::cout << "test2 will be called..." << std::endl; }
        (this->*this->m.at(s))();
    }
};

int main()
{
    Test t;
    t.dispatch("test1");
    t.dispatch("test2");
}

输出

test1将被调用...

test1将被调用...

当优化启用时,这是真的很奇怪。发生了什么?

when optimizations are enabled, which is really bizarre. What's going on?

推荐答案

结果是Visual C ++的链接器可以将具有相同定义的函数合并为一个。

根据C ++,这是否合法,我不知道;它影响可观察的行为,所以它看起来像一个bug给我。有更多信息的其他人可能希望在这个问题上。

It turns out Visual C++'s linker can merge functions with identical definitions into one.
Whether that's legal or not according to C++, I have no idea; it affects observable behavior, so it looks like a bug to me. Someone else with more information may want to chime in on that though.

这篇关于为什么(成员)函数指针在Visual C ++中表现如此奇怪?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 06:41