为什么(成员)函数指针在 Visual C++ 中表现得如此怪异? [英] Why are (member) function pointers behaving so weirdly in Visual C++?

查看:13
本文介绍了为什么(成员)函数指针在 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 将被调用...

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆