c++ - 为什么显式模板实例化会在存在外线虚拟时导致 weak-template-vtables 警告?

标签 c++ c++11 templates clang++

[编辑以显示 .cpp 和 hpp 之间的拆分]

// file.hpp
class Base {
 public:
    virtual ~Base(void);
    Base(void);
    Base(const Base&) = default;
};

template<typename T>
class Derived: public Base {
 public:
    Derived(void);
    bool func(void);
};
// file.cpp
#include "file.hpp"

Base::~Base(void) {}
Base::Base(void) {}

template<typename T>
bool Derived<T>::func(void) {return true;}

template<typename T>
Derived<T>::Derived(void) {}

// required to avoid linker errors when using `Derived` elsewhere
template class Derived<int>;

最后一行在 Clang v8.0 中导致以下编译器警告 warning: explicit template instantiation 'Derived<int>' will emit a vtable in every translation unit [-Wweak-template-vtables]

我的理解是因为Base至少有一个外联虚方法,这里所有类的 vtables 都将锚定到这个翻译单元,因此 this guidance在 LLVM 编码标准中。 那么为什么会生成此警告?

在 Godbolt 上查看我正在使用的特定编译器版本:https://godbolt.org/z/Kus4bq

我在 SO 上发现的每个类似问题都是针对没有外联虚拟方法的类,因此我无法找到答案。

最佳答案

编辑:我认为这不是 Clang 中的错误,而是 Itanium C++ ABI 要求的结果:https://itanium-cxx-abi.github.io/cxx-abi/abi.html#vague-itemplate此部分在 computeKeyFunction 中的 RecordLayoutBuilder.cpp 中的 Clang 源代码中引用:

Template instantiations don't have key functions per Itanium C++ ABI 5.2.6. Same behaviour as GCC.

Itanium 规范指出类模板实例化将存储在目标文件的 COMDAT 部分中。 COMDAT 部分用于存储同一对象的多个定义,然后可以在链接时统一这些定义。如果模板按照我在回答中预期的方式编译,并通过一个关键函数将其锚定到特定的翻译单元,那么这将不符合此 ABI。

我确实认为该警告没有帮助,但由于它不是 -Wall 或 -Wextra 的一部分,所以我不太介意。

(以下为原帖)

我倾向于认为这是由于 Clang 中的错误所致,此处报告:https://bugs.llvm.org/show_bug.cgi?id=18733

如果链接断开,请在此处重新发布内容:

Rafael Ávila de Espíndola 2014-02-05 00:00:19 PST

Given

template<typename T>
class foo {
  virtual ~foo() {}
};

extern template class foo<int>;
template class foo<int>;

clang warns:

test.cpp:6:23: warning: explicit template instantiation 'foo<int>' will emit a vtable in every translation unit [-Wweak-template-vtables]
extern template class foo<int>;
                      ^
1 warning generated.

note that the warning points to the explicit template instantiation declaration, but is triggered by the definition. This should probably be checking if the definition is in a header. In a .cpp file there is only one translation unit that sees it.

Comment 1 David Faure 2016-02-13 12:21:27 PST

Yes, this false positive is indeed annoying. Thanks for reporting it. Clang developers: thanks for fixing it :-)

对于其他人的意见,我将不胜感激,但我同意错误报告者的观点,即在这种情况下,此警告似乎是虚假的。

尽管错误报告的最后评论称它已修复,但该错误仍以"new"状态列出,所以我不认为它已修复。

关于c++ - 为什么显式模板实例化会在存在外线虚拟时导致 weak-template-vtables 警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56041900/

相关文章:

templates - 在grails中包含 View 与渲染模板

c++ - 包含来自另一个文件的函数会产生范围错误(openFoam)

c++ - 从 C++ 中的 .obj 文件中读取整数

c++ - 将 emplace 与 std::fill 等算法一起使用

c++ - 避免硬编码枚举类型

c++ - 将普通功能更改为模板会产生任何正/负差异吗?

c++ - 我如何使用具有继承和模板的友元类

c++ - 命名空间中定义的类中的友元函数

c++ - 如何从另一个源文件调用 main.cpp 中的静态函数?

templates - Go html模板如何从funcMap获取函数中的用户IP