c++ - 某种类型别名 : An empty derived class

标签 c++ inheritance types alias downcast

我想知道的是:

  • 此代码段是否可移植?
  • 如果不是,为什么?

struct GenericBase{
};

struct MyObject : public GenericBase{
    virtual void method() = 0;
};

struct MyAlias : public MyObject{
    //supposed to have exactly the same layout as MyObject (?)
};

struct MyImpl : public MyObject{
    virtual void method() { cout << "method implementation \n"; }
    //note that MyImpl inherit MyObject, but we cast it to MyAlias
};

void test_alias(){
    MyImpl m;
    GenericBase* ptr = &m;
    MyAlias* new_ptr = static_cast<MyAlias*>(ptr); //here is the cast
    new_ptr->method();
}

编辑:
我不能使用 RTTI,也不能使用模板

最佳答案

回答:这不是可移植的。

struct MyAlias : public MyObject{
    //supposed to have exactly the same layout as MyObject (?)
};

这个评论是错误的:MyAlias 的大小是依赖于实现的,并且不是由标准指定的(例如,它取决于目标体系结构的对齐要求:编译器可能会在派生对象中添加填充位,或者关于如何实现方法调度等。)

关于c++ - 某种类型别名 : An empty derived class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24148422/

相关文章:

Java无限递归自引用类型

haskell - 如何将指定为自由单子(monad)的程序与预期指令的描述进行比较?

c++ - 引用类型示例问题

c++ - 我是否需要为 C++ 中的每个函数实现指定类

c++ - 我应该返回 gsl::span<const T> 而不是 const std::vector<T>&

Python属性描述符设计: why copy rather than mutate?

通过构造函数为 vector 预分配 C++ 内存失败

java - 这段代码的输出是什么以及如何输出?

Javascript 类 : how to access overridden parent class functions in parent class code

c - 字段有不完整的类型错误