【发布时间】:2018-08-01 01:25:32
【问题描述】:
#include <cstdio>
#include <cstdlib>
struct Interface {
virtual void f() = 0;
};
struct Impl1: Interface {
void f() override {
std::puts("foo");
}
};
// or __attribute__ ((visibility ("hidden")))/anonymous namespace
static Interface* const ptr = new Impl1 ;
int main() {
ptr->f();
}
当用g++-7 -O3 -flto -fdevirtualize-at-ltrans -fipa-pta -fuse-linker-plugin编译时,上面的ptr->f()调用不能被去虚拟化。
似乎没有外部库可以修改ptr。这是 GCC 优化器的缺陷,还是因为某些其他来源在这种情况下使去虚拟化不可用?
【问题讨论】:
-
您想解决的实际问题是什么?你为什么做这个?也许对实际问题有更好或其他的解决方案?请花点时间read about the XY problem。
-
如果将
ptr放入匿名命名空间会发生什么? -
@Bathsheba 在 Godbolt 上试过。仍然是虚拟通话。
-
很奇怪。本来以为 gcc 在这种情况下会应用 -fdevirtualize-at-ltrans :它是简单的标准 C++。好问题。
-
使用这样的匿名命名空间似乎可以启用去虚拟化:godbolt.org/g/exzQrC
标签: c++ gcc compiler-optimization