【发布时间】:2019-11-09 00:02:26
【问题描述】:
我试图找到一种静态断言派生类指针可以安全地重新解释为指向基类的指针的方法,但遇到了意想不到的事情:
我预计以下代码中的两个静态断言会失败。
class Base1 {
int x;
};
class Base2 {
int y;
};
class Derived : public Base1, public Base2 {
int z;
};
// one of these should fail???
static_assert( (Derived *)nullptr == (Base1 *)nullptr, "err1" );
static_assert( (Derived *)nullptr == (Base2 *)nullptr, "err2" );
// and one of these as well???
static_assert( (Base1 *)(Derived *)nullptr == nullptr, "err3" );
static_assert( (Base2 *)(Derived *)nullptr == nullptr, "err3" );
对于第一对断言,由于它的参数类型为 Derived* 和 Base1*/Base2*,我预计 Derived* 会隐式转换为 Base1* 或 Base2*比较。由于Base1 和Base2 不能占用相同的内存,因此它们不能都位于Derived 对象占用的内存的开头,因此其中一个转换应该增加了指针值。那么不应该发现非零指针等于null。
同样,对于第二对,我希望显式转换为 Base1* 和 Base2* 应该改变了其中一个指针,但它们仍然比较等于 null。
这是怎么回事?
【问题讨论】:
-
这就像问为什么
int a = 0; long b = 0; static_assert(a == b);有效。你所有的点都等于nullptr,所以它们应该都是一样的。 -
我认为 nullptr 总是相同的值。并且铸造它们在这种情况下没有效果。见stackoverflow.com/a/44117520/7834933
-
但是,如果这些不是 nullptr,这将产生预期的效果。
标签: c++ multiple-inheritance static-assert