C++ 为什么这个结构需要24个字节 模板 结构八叉树{ std::变量数据; 布尔岛; } sizeof(八叉树型)
我用的是x64clang10。C++ 为什么这个结构需要24个字节 模板 结构八叉树{ std::变量数据; 布尔岛; } sizeof(八叉树型),c++,memory,types,C++,Memory,Types,我用的是x64clang10。 我认为variant需要8个字节,aligned boolean需要8个字节。要区分存储的类型std::variant包含一个计算遗漏的额外整数值 template<typename T> struct OctreeNode { std::variant<std::unique_ptr<OctreeNode<T>[]>, std::unique_ptr<T>> data;
我认为variant需要8个字节,aligned boolean需要8个字节。要区分存储的类型
std::variant
包含一个计算遗漏的额外整数值
template<typename T>
struct OctreeNode {
std::variant<std::unique_ptr<OctreeNode<T>[]>, std::unique_ptr<T>> data;
bool isLeaf;
}
sizeof(OctreeNode<int>)
#包括
#包括
样板
结构八叉树{
std::变量数据;
布尔岛;
};
样板
结构OctreeNodeAltVariant{
无符号字符索引;
联合{
std::唯一的ptr a;
std::唯一的ptr b;
};
};
样板
结构OctreeNodeAlt{
八进制变异数据;
布尔岛;
};
静态_断言(sizeof(OctreeNode)==sizeof(OctreeNodeAlt));
要想问一个更好的问题,请解释你为什么这么想。你是怎么得出这个结论的?引用您的源代码。来自cppreference:类模板std::variant表示类型安全联合。std::unique_ptr使用的内存与原始指针一样多。所以我没有意识到std::variant状态开销。
#include <variant>
#include <memory>
template<typename T>
struct OctreeNode {
std::variant<std::unique_ptr<OctreeNode<T>[]>, std::unique_ptr<T>> data;
bool isLeaf;
};
template<typename T>
struct OctreeNodeAltVariant {
unsigned char index;
union {
std::unique_ptr<OctreeNode<T>[]> a;
std::unique_ptr<T> b;
};
};
template<typename T>
struct OctreeNodeAlt {
OctreeNodeAltVariant<T> data;
bool isLeaf;
};
static_assert(sizeof(OctreeNode<int>) == sizeof(OctreeNodeAlt<int>));