【发布时间】:2020-03-22 16:47:13
【问题描述】:
我从这个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.
【问题讨论】:
-
b未初始化,因此您的程序具有未定义的行为 -
reinterpret_cast<A&>(b).avg表现出未定义的行为,通过在对象(A类型)的生命周期开始之前访问它。 -
@IgorTandetnik - 我根本不看 cout 的输出 - 我更喜欢看 gdb 和 sizeof。请让我知道它是如何由未初始化的 b 控制的。另请查看两种情况下 a 和 b 的定义。
标签: c++ c++11 templates c++14 generic-programming