Why can't gcc devirtualize this function call?

后端 未结 2 1985
误落风尘
误落风尘 2020-12-30 22:38
#include 
#include 
struct Interface {
    virtual void f() = 0;
};

struct Impl1: Interface {
    void f() override {
        std::puts         


        
2条回答
  •  无人及你
    2020-12-30 22:58

    I just made an other experiment, as in Omnifarious answer. But this time I make the pointer point to a static object:

    Impl1 x;
    static Interface* const ptr = &x ;
    

    GCC do devirtualize the function call, -O2 is sufficient. I don't see any rule in the C++ standard that would make pointer to static storage treated differently than pointer to dynamic storage.

    It is allowed to change the object at the address pointed to by ptr. So the compiler must track what is happening at that address to know what is the actual dynamic type of the object. So my opinion is that optimizer implementer may have considered that tracking what is happening on the heap would be too difficult in real program, so the compiler just don't do it.

提交回复
热议问题