The following code gives different results in version 2013 2013 / Debug

is this a bug in VS 2013 compiler?
The following code gives different results in debugging and release.
In debugging, the result will be as expected, but in its release will be "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");
    }

}
+4
source share
1 answer

This is due to compiler optimization.

It seems that the compiler should perform such optimization, is a discussion. Do different functions have different 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");
}

, /OPT: ICF , , .

/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");
    }
}
+1

All Articles