为什么这 2 个具有相同内容的结构对于 Clang 来说不是布局兼容类型,而向量对于 MSVC 不起作用

dou*_*oug 6 c++ language-lawyer

更新:刚刚将 MSVC 编译器更新到 17.4.5。MSVC 现在表示 和AAz发布模式下兼容的类型,但当std::vector包含在结构中时,在调试模式下不兼容。真奇怪。可能与向量的大小差异有关。Release 模式下的向量由预期的 3 个指针组成。在调试模式下,它通过一个附加指针进行扩展,该指针似乎是为了某种附加使用验证而添加的。

根据布局兼容类型的描述,结构体 A 和结构体 Az 应该符合资格,因为结构体内容是相同的。

如果 T1 和 T2 是相同类型、布局兼容枚举或布局兼容标准布局类类型,则两种类型 cv1 T1 和 cv2 T2 是布局兼容类型。

Clang 无法编译,因为std::is_layout_compatible未实现。对于 和vectorintgcc 可以工作并返回 true,is_layout_compatible而 MSVC 在发布模式下返回 true,但在调试模式下返回 false。

编译器资源管理器 int 和矢量编译器资源管理器 int

#include <memory>
#include <iostream>
#include <vector>
#include <type_traits>

struct Az {
    std::vector<int> v;
    int i;
};

struct A {
    std::vector<int> v;
    int i;
};

int main()
{
    std::cout << "sizeof:" << sizeof(A) << " Layout_compatible:" << std::is_layout_compatible_v<A, Az> << '\n';
}


MSVC 2022 Output Debug mode:
sizeof:40 Layout_compatible:0

MSVC 2022 Output Release mode:
sizeof:32 Layout_compatible:1
Run Code Online (Sandbox Code Playgroud)