我从此link复制了以下程序
#include <iostream>
#include <type_traits>
struct A { // non-POD type
int avg;
A (int a, int b) : avg((a+b)/2) {}
};
typedef std::aligned_storage<sizeof(A),alignof(A)>::type A_pod;
int main() {
A_pod a,b;
new (&a) A (10,20);
b=a;
std::cout << reinterpret_cast<A&>(b).avg << std::endl;
return 0;
}
我在此代码上运行gdb以了解各种成分的大小,结果如下:
(gdb) b 18
Breakpoint 1 at 0x96d: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage.cpp:18. (3 locations)
(gdb) r
Starting program: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage
Breakpoint 1, _GLOBAL__sub_I_main () at aligned_storage.cpp:18
18 }
(gdb) ptype a
type = const union {
int i[2];
double d;
}
(gdb) ptype A_pod
type = union std::aligned_storage<4, 4>::type {
unsigned char __data[4];
struct {
<no data fields>
} __align;
}
(gdb) ptype A_
No symbol "A_" in current context.
(gdb) ptype A
type = struct A {
int avg;
public:
A(int, int);
}
(gdb) p sizeof(A)
$1 = 4
(gdb) p sizeof(a)
$2 = 8
(gdb) p sizeof(b)
$3 = 8
(gdb) ptype A
type = struct A {
int avg;
public:
A(int, int);
}
稍后看到普通的构造函数调用,我在main()中添加了一行以按如下方式构造对象c-
int main() {
A_pod a,b;
A c(10,20);
new (&a) A (10,20);
b=a;
std::cout << reinterpret_cast<A&>(b).avg << std::endl;
return 0;
}
这导致a和b的大小甚至类型定义更改。即使注释掉了这一新添加的行,编译器也具有不同的行为,这是非常令人惊讶的。
(gdb) r
Starting program: /home/ripunjay/study/bitbucket/study/cpp/aligned_storage
15
Breakpoint 1, main () at aligned_storage.cpp:18
18 return 0;
(gdb) ptype a
type = union std::aligned_storage<4, 4>::type {
unsigned char __data[4];
struct {
<no data fields>
} __align;
}
(gdb) ptype b
type = union std::aligned_storage<4, 4>::type {
unsigned char __data[4];
struct {
<no data fields>
} __align;
}
(gdb) ptype A_pod
type = union std::aligned_storage<4, 4>::type {
unsigned char __data[4];
struct {
<no data fields>
} __align;
}
g++ --version
g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 Copyright (C) 2017 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
通过执行此std::cout << reinterpret_cast<A&>(b).avg << std::endl;
,您的程序表现出未定义的行为。为什么?您使用未初始化的值。
这意味着什么?该编译器可以执行任何操作。我所说的任何东西,包括字面上的炸毁您的计算机,这都是标准所允许的。因此,在gdb中看到类型大小/填充/对齐方式等的变化也就不足为奇了。自从您进入了未防御行为的领域以来,编译器就可以这样做。
恕我直言,但是由于UB大小/ class A
的对齐方式的变化,因此没有简单的方法可以确定。由于它更改了std::aligned_storage
的内部,因此也随之更改(因为对齐的存储内部对于不同的大小/对齐对可能具有非常不同的内部表示形式。)>