【发布时间】:2023-03-27 09:40:01
【问题描述】:
我在使用 Clang 为 x64 编译的 C++17 中有一个小的内存问题。由于我使用低级内存副本到专用硬件,因此我确实依赖于按预期对齐的内存。我最近从 Visual Studio 迁移到 Clang,遇到了以下问题:
见以下代码:
struct ContainerRoot{};
template<size_t t_size, class t_type>
struct Container : public ContainerRoot
{
t_type contents[t_size];
};
static_assert(sizeof(Container<1, double>) == 8); //This works as expected
static_assert(sizeof(Container<4, double>) == 32); //This works as expected
static_assert(sizeof(Container<16, double>) == 128); //This works as expected
static_assert(sizeof(Container<4, Container<4, double>>) == 128); //This fails.
在上面的例子中 sizeof(Container
到目前为止,我已经使用 std::is_polymorphic>>() 进行了检查,只是为了确认没有将一些虚拟查找表添加到类中。
【问题讨论】:
-
Container<Container<double>>不应该编译:Container需要两个模板参数。 -
对不起,我试图做一个简单的例子。实际上没有测试编译。稍微整理了一下示例。
-
鉴于
Container实际上继承自某些东西:RTTI 是否已激活?如果是这样,编译器可能会添加一个空的 vftable,只是为了知道它处理的是哪种类型。还解释了不同编译器的不同行为。奇怪的是:在这种情况下,我预计会有更多的开销。 -
有趣:即使 RTTI 被停用也会失败。但请注意:
sizeof(Container<4,double>[4]) == 128。如果继承被删除,也可以工作。似乎是空基类优化的问题(en.cppreference.com/w/cpp/language/ebo)。
标签: c++ templates memory clang padding