为什么(成员)函数指针在 Visual C++ 中表现得如此怪异?

2022-01-11 00:00:00 visual-c++ linker 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 将被调用...

test1 will be called...
test1 will be called...

当启用优化时,这真的很奇怪.怎么回事?

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

推荐答案

原来 Visual C++ 的链接器可以将具有相同定义的函数合并为一个.
根据 C++ 是否合法,我不知道;它会影响可观察的行为,所以对我来说它看起来像一个错误.不过,其他有更多信息的人可能想插话.

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.

相关文章