The size of any object or member subobject is required to be at least 1 even if the type is an empty class type [...], in order to be able to guarantee that the addresses of distinct objects of the same type are always distinct.
这个我就知道了。我刚发现的是一些库类型,如 std::tuple
不使用任何大小来包含空类。这是真的?如果是,那怎么样?
编辑:在阅读了@bolov 对他的回答的最后注释后,我还有一个问题:因为Empty
是POD
所以memcpy
是安全的它。但是,如果您将 memcpy 到一个“幻影”地址(请参阅@bolov 的回答),您将有效地写入 int
元素(sizoef(Empty)
为 1)。这似乎不太对。
最佳答案
对象 的大小必须大于零。 子对象 的大小没有该限制。这导致了空基优化 (EBO),其中空基类不占用空间(编译器在将近 20 年前开始实现)。而这反过来又导致将 std::tuple
通常实现为继承链,其中空基类不占用空间。
关于c++ - std::tuple 中的空类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039458/