假设我有以下结构:
template <typename T>
struct Wrapper {
virtual T* get() const = 0;
protected:
void *c_;
};
template <typename C, typename T>
struct WrapperOf: Wrapper<T> {
WrapperOf(C *c = 0) : c_(c) { }
virtual T* get() const {
C *c = static_cast<C*>(c_);
return static_cast<T*>(c->get());
}
};
标准是否保证任何 WrapperOf
的大小都相同?通常,我可以执行以下操作吗:
struct Dummy { void* get(); };
struct Real { int* get(); };
char storage[sizeof(WrapperOf<Dummy, void>)];
Wrapper<int> *wp =
new(storage) WrapperOf<Real, int>();
如果我专门研究 WrapperOf
,通常:
template <>
struct WrapperOf<void, void>: Wrapper<void> {
virtual void* get() const { return 0; }
};
使用它来初始化存储(避免有一个Dummy
类):
char storage[sizeof(WrapperOf<void, void>)];
这仍然有效吗?
最佳答案
来自当前工作草案N4640 (2017-02-06)
5.3.3 Sizeof [expr.sizeof]
The sizeof operator yields the number of bytes in the object representation of its operand.
... When applied to a class, the result is the number of bytes in an object of that class including any padding required for placing objects of that type in an array.
所以没有任何保证,只是它需要多少字节。
即使对于大多数基本类型,标准也表示它是实现定义的
- ... sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1. The result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined.
可以推断出某个类需要 N 个字节,并且根据经验可以看出,对于给定实现中的一系列派生类,它是相同的。只是没有保证。
关于c++ - 没有新成员的模板化多态派生类的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544550/