加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 以下代码在VS 2013 Release / Debug 中产生不同的结果

发布时间:2020-12-16 07:12:04 所属栏目:百科 来源:网络整理
导读:参见英文答案 Do distinct functions have distinct addresses?????????????????????????????????????4个 这是VS 2013编译器中的错误吗? 以下代码在调试和发布中产生不同的结果. 在调试中,结果如预期,但在发布时它是“A” #include cstdiostruct A{ virtual
参见英文答案 > Do distinct functions have distinct addresses?????????????????????????????????????4个
这是VS 2013编译器中的错误吗?
以下代码在调试和发布中产生不同的结果.
在调试中,结果如预期,但在发布时它是“A”

#include <cstdio>

struct A
{
    virtual void* getClass() { return A::ID; };
    static void ID(){};
};

struct B : public A
{
    virtual void* getClass() { return B::ID; };
    static void ID(){};
};

struct C : public A
{
    virtual void* getClass() { return C::ID; };
    static void ID(){};
};


int main(int argc,char *argv[])
{
    A* d = new C;

    if (d->getClass() == A::ID)
    {
        printf("A");
    }
    else if (d->getClass() == B::ID)
    {
        printf("B");
    }
    else if (d->getClass() == C::ID)
    {
        printf("C");
    }

}

解决方法

这是由于编译器优化.

似乎编译器是否应该执行这种优化是值得商榷的Do distinct functions have distinct addresses? .

typeid的

更传统的方法是使用typeid来验证运行时类型.请注意,您取消引用指针以获取派生类的类型.

if (typeid(*d) == typeid(A))
{
    printf("A");
}
else if (typeid(*d) == typeid(B))
{
    printf("B");
}
else if (typeid(*d) == typeid(C))
{
    printf("C");
}

禁用优化

However,because /OPT:ICF can merge identical data or functions,it can change the function names that appear in stack traces.

您可以在发布中使用/ OPT:NOICF来防止该行为.

此外,您可以看到实际上以不同方式实现这些功能会使其按预期工作.

示例代码

#include <string>

struct A
{
    virtual std::string getClass() { return A::ID(); }
    static std::string ID(){ return "A"; }
};

struct B : public A
{
    virtual std::string getClass() { return B::ID(); }
    static std::string ID(){ return "B"; }
};

struct C : public A
{
    virtual std::string getClass() { return C::ID(); }
    static std::string ID(){ return "C"; }
};

int main(int argc,char *argv[])
{
    A* d = new C;

    if (d->getClass() == A::ID())
    {
        printf("A");
    }
    else if (d->getClass() == B::ID())
    {
        printf("B");
    }
    else if (d->getClass() == C::ID())
    {
        printf("C");
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读