c++ - 没有新成员的模板化多态派生类的大小

标签 c++ templates polymorphism sizeof placement-new

假设我有以下结构:

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]

  1. The sizeof operator yields the number of bytes in the object representation of its operand.

  2. ... 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.

所以没有任何保证,只是它需要多少字节。

即使对于大多数基本类型,标准也表示它是实现定义的

  1. ... 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/

相关文章:

c++ - 从派生类实现基类构造函数的专门化的替代方法是什么?

c++ - 重新设计附加代码段的建议

C++11 和多态 lambda 的缺失——为什么?

c++ - 有没有办法将 8bitX32 ymm 寄存器向右/向左移动 N 个位置(C++)

c++ - 巨大的斐波那契模 m C++

c++ - 如何获得 vector 中的最大值或最小值?

templates - D中解析模板元组参数

c++ - 模板类中的静态成员

c++ - 在 C++ 函数中创建新对象导致程序崩溃

C++ 模板与 STL 返回类型相结合