不知道大家读过《Modern C++ std::unique_ptr的实现原理》没有?
里面提到了std::tuple<void*, default_delete()>的大小是4,而不是4+1或者4+4,是不是很奇怪,本文不会揭晓答案,只是会扩展测试各种情况。
#include<iostream>
#include <tuple>
using namespace std;
struct Empty{
constexpr Empty() noexcept = default;
};
int main(){
std::cout<<"sizeof(Empty):"<<sizeof(Empty)<<std::endl;
std::cout<<"sizeof(std::tuple<int,Empty>):"<<sizeof(std::tuple<int,Empty>)<<std::endl;
std::cout<<"sizeof(std::tuple<int,Empty,Empty,int>):"<<sizeof(std::tuple<int,Empty,Empty,int>)<<std::endl;
std::cout<<"sizeof(std::tuple<int,Empty,Empty,Empty,Empty,int>):"<<sizeof(std::tuple<int,Empty,Empty,Empty,Empty,int>)<<std::endl;
std::cout<<"sizeof(std::tuple<int,Empty,Empty,Empty,Empty,Empty>):"<<sizeof(std::tuple<int,Empty,Empty,Empty,Empty,Empty>)<<std::endl;
std::cout<<"sizeof(Empty[100]):"<<sizeof(Empty[100])<<std::endl;
}
有兴趣的同学试着运行一下?
答案是:
sizeof(Empty):1
sizeof(std::tuple<int,Empty>):4
sizeof(std::tuple<int,Empty,Empty,int>):12
sizeof(std::tuple<int,Empty,Empty,Empty,Empty,int>):12
sizeof(std::tuple<int,Empty,Empty,Empty,Empty,Empty>):8
sizeof(Empty[100]):100