tl,dr 这更加增加了我对库实现者的尊重。一旦您开始思考如何实现这一点,他们为实现std::tuple 的优化而必须遵循的规则令人敬畏。
我自然而然地继续玩了一会儿,看看情况如何。
设置:
struct Empty {};
template <class T> auto print_mem(const T& obj)
{
cout << &obj << " - " << (&obj + 1) << " (" << sizeof(obj) << ")" << endl;
}
测试:
int main() {
std::tuple<int> t_i;
std::tuple<Empty> t_e;
std::tuple<int, Empty, Empty> t_iee;
std::tuple<Empty, Empty, int> t_eei;
std::tuple<int, Empty, Empty, int> t_ieei;
cout << "std::tuple<int>" << endl;
print_mem(t_i);
cout << endl;
cout << "std::tuple<Empty>" << endl;
print_mem(t_e);
cout << endl;
cout << "std::tuple<int, Empty, Empty" << endl;
print_mem(t_iee);
print_mem(std::get<0>(t_iee));
print_mem(std::get<1>(t_iee));
print_mem(std::get<2>(t_iee));
cout << endl;
cout << "std::tuple<Empty, Empty, int>" << endl;
print_mem(t_eei);
print_mem(std::get<0>(t_eei));
print_mem(std::get<1>(t_eei));
print_mem(std::get<2>(t_eei));
cout << endl;
print_mem(t_ieei);
print_mem(std::get<0>(t_ieei));
print_mem(std::get<1>(t_ieei));
print_mem(std::get<2>(t_ieei));
print_mem(std::get<3>(t_ieei));
cout << endl;
}
结果:
std::tuple<int>
0xff83ce64 - 0xff83ce68 (4)
std::tuple<Empty>
0xff83ce63 - 0xff83ce64 (1)
std::tuple<int, Empty, Empty
0xff83ce68 - 0xff83ce6c (4)
0xff83ce68 - 0xff83ce6c (4)
0xff83ce69 - 0xff83ce6a (1)
0xff83ce68 - 0xff83ce69 (1)
std::tuple<Empty, Empty, int>
0xff83ce6c - 0xff83ce74 (8)
0xff83ce70 - 0xff83ce71 (1)
0xff83ce6c - 0xff83ce6d (1)
0xff83ce6c - 0xff83ce70 (4)
std::tuple<int, Empty, Empty, int>
0xff83ce74 - 0xff83ce80 (12)
0xff83ce7c - 0xff83ce80 (4)
0xff83ce78 - 0xff83ce79 (1)
0xff83ce74 - 0xff83ce75 (1)
0xff83ce74 - 0xff83ce78 (4)
Ideone link
我们可以从一开始就看到
sizeof(std:tuple<Empty>) == 1 (because the tuple cannot be empty)
sizeof(std:tuple<int>) == 4
sizeof(std::tuple<int, Empty, Empty) == 4
sizeof(std::tuple<Empty, Empty, int) == 8
sizeof(std::tuple<int, int>) == 8
sizeof(std::tuple<int, Empty, Empty, int>) == 12
我们可以看到,有时确实没有为Empty 保留空间,但在某些情况下,1 byte 被分配给Empty(其余为填充)。当Empty 元素是最后一个元素时,它看起来可能是0。
仔细检查通过get 获得的地址,我们可以看到从来没有两个Empty 元组元素具有相同的地址(这符合上述规则),即使这些地址(Empty)看起来在int 元素内。此外,Empty 元素的地址不在容器元组的内存位置之外。
这让我想到:如果我们的尾随 Empty 比 sizeof(int) 多怎么办。这会增加元组的大小吗?确实如此:
sizeof(std::tuple<int>) // 4
sizeof(std::tuple<int, Empty>) // 4
sizeof(std::tuple<int, Empty, Empty>) // 4
sizeof(std::tuple<int, Empty, Empty, Empty>) // 4
sizeof(std::tuple<int, Empty, Empty, Empty, Empty>) // 4
sizeof(std::tuple<int, Empty, Empty, Empty, Empty, Empty>) // 8 yep. Magic
最后一点:Empty 元素有“幻像”地址是可以的(它们似乎与int 元素“共享”内存)。由于Empty是一个……嗯……空类,它没有非静态数据成员,这意味着为它们获得的内存无法访问。