【发布时间】:2015-12-22 13:08:37
【问题描述】:
我有这个类层次结构:
class Base {
// no virtual stuff
}
class Property : Base {
// no virtual stuff
}
typedef const Property* PropertyID;
template<typename T>
class TypedProperty : public Property {
// One virtual method
virtual bool ValidateValue(T& value) const { return true; }
inline const T& GetDefaultValue() const { return m_default_value; }
}
然后它是这样使用的:
template<typename T>
const T& DoSomething(PropertyID property) {
return reinterpret_cast<const TypedProperty<T>*>(property)->GetDefaultValue();
}
Clang 吐出这个警告:
警告:'reinterpret_cast' 到类 'const TypedProperty *' 从其基类以非零偏移量'PropertyID'(又名'const Property *')的行为不同于'static_cast' [-Wreinterpret-base-class]
Xcode 中的“Fix-it”表示:
在向下转换时使用“static_cast”正确调整指针。
这是什么意思,尤其是“从非零偏移的基数”部分?
使用reinterpret_cast 与static_cast 实际会出现什么问题:它只是(正确地AFAIK)转换指针?我知道传递的对象是const TypedProperty<T>*。
【问题讨论】:
-
实际上可能很少涉及指针运算(想想 vtable、多重继承……)
-
@Jarod42:理论上,但不是在这种情况下;也许编译器警告过于悲观?
-
@JohnZwinck:为什么不使用安全的方式?并且 OP 没有显示所有代码(因为他试图调用未声明的
GetDefaultValue()) -
@Jarod42:当然,这里首选 static_cast。我并不是要暗示我认为代码是最优的。
-
@Pol: small Demo 显示差异。