假设我有一个简单的多态继承:
struct Base
{
virtual void exec() { std::cout << "base" << std::endl; }
virtual ~Base() { }
};
struct Derived1 : public Base
{
void exec() override { std::cout << "derived1" <<std::endl; }
};
struct Derived2 : public Base
{
void exec() override { std::cout << "derived2" << std::endl; }
};
我还有一个模板Wrapper
存储一些通用数据的类:
template<typename T> struct Wrapper : public T
{
bool b{true};
};
我可以安全地从 Wrapper<Derived1>
转换吗?至 Base
来自 Base
至 Wrapper<Derived1>
使用以下转换?
template<typename T> auto& asWrapper(T& mX)
{
return static_cast<Wrapper<T>&>(mX);
}
template<typename T, typename TWrapper> auto& asT(TWrapper& mX)
{
return reinterpret_cast<T&>(mX);
}
似乎可行的示例:
int main()
{
auto d1 = std::make_unique<Wrapper<Derived1>>();
auto d2 = std::make_unique<Wrapper<Derived2>>();
Base* bd1 = d1.get();
Base* bd2 = d2.get();
bd1->exec();
bd2->exec();
auto& bl1 = asWrapper(*bd1);
auto& bl2 = asWrapper(*bd2);
std::cout << bl1.b << " " << bl2.b << std::endl;
bl1.b = false;
std::cout << bl1.b << " " << bl2.b << std::endl;
bl2.b = false;
std::cout << bl1.b << " " << bl2.b << std::endl;
asT<Derived1>(bl1).exec();
asT<Derived2>(bl2).exec();
return 0;
}
可执行示例:http://ideone.com/MRy9Hy
这似乎可行,但我不相信这种方法的安全性。它符合标准吗?它会导致未定义的行为吗?
最佳答案
包装器
N4140 [expr.static.cast]/2:
An lvalue of type “cv1
B
,” whereB
is a class type, can be cast to type “reference to cv2D
,” whereD
is a class derived (Clause 10) fromB
, if a valid standard conversion from “pointer toD
” to “pointer toB
” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, andB
is neither a virtual base class ofD
nor a base class of a virtual base class ofD
. The result has type “cv2D
.” An xvalue of type “cv1B
” may be cast to type “rvalue reference to cv2D
” with the same constraints as for an lvalue of type “cv1B
.” If the object of type “cv1B
” is actually a subobject of an object of typeD
, the result refers to the enclosing object of typeD
. Otherwise, the behavior is undefined.
所以你的函数aswrapper
仅当 T&
时才定义行为传递给它实际上是指一个T
Wrapper<T>
的基础对象.示例程序中的两个调用都将 Base&
至 Wrapper<Base>&
, 但两个参数实际上都不是 Wrapper<Base>&
的基础对象,因此结果行为是未定义的。
作为T
[expr.reinterpret.cast]:
...
7 An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue
v
of object pointer type is converted to the object pointer type “pointer to cvT
”, the result isstatic_cast<cv T*>(static_cast<cv void*>(v))
. Converting a prvalue of type “pointer toT1
” to the type “pointer toT2
” (whereT1
andT2
are object types and where the alignment requirements ofT2
are no stricter than those ofT1
) and back to its original type yields the original pointer value....
11 A glvalue expression of type
T1
can be cast to the type “reference toT2
” if an expression of type “pointer toT1
” can be explicitly converted to the type “pointer toT2
” using areinterpret_cast
. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference castreinterpret_cast<T&>(x)
has the same effect as the conversion*reinterpret_cast<T*>(&x)
with the built-in&
and*
operators (and similarly forreinterpret_cast<T&&>(x)
). —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.
所以 asT<T>(WrapperT& foo)
相当于*reinterpret_cast<T*>(&foo)
相当于*static_cast<T*>(static_cast<void*>(&foo))
.指向 Wrapper<Base>
的指针当然可以转换为 void*
根据 [expr.static.cast]/4:
An expression
e
can be explicitly converted to a typeT
using astatic_cast
of the formstatic_cast<T>(e)
if the declarationT t(e);
is well-formed, for some invented temporary variablet
(8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion. The expressione
is used as a glvalue if and only if the initialization uses it as a glvalue.
因为任何指针类型都隐式转换为 void*
每 [conv.ptr]/2:
A prvalue of type “pointer to cv
T
,” whereT
is an object type, can be converted to a prvalue of type “pointer to cvvoid
”. The result of converting a non-null pointer value of a pointer to object type to a “pointer to cvvoid
” represents the address of the same byte in memory as the original pointer value. The null pointer value is converted to the null pointer value of the destination type.
那个void*
可以通过 [expr.static.cast]/13 转换为任何对象指针类型:
A prvalue of type “pointer to cv1
void
” can be converted to a prvalue of type “pointer to *cv*2T
,” whereT
is an object type and cv2 is the same cv-qualification as, or greater cv-qualification than, cv1. The null pointer value is converted to the null pointer value of the destination type. If the original pointer value represents the addressA
of a byte in memory andA
satisfies the alignment requirement ofT
, then the resulting pointer value represents the same address as the original pointer value, that is,A
. The result of any other such pointer conversion is unspecified. A value of type pointer to object converted to “pointer to cvvoid
” and back, possibly with different cv-qualification, shall have its original value.
鉴于上述asT
格式正确——你已经知道了,因为编译器没有诊断它。但是,自Wrapper<Base>
对齐以来,示例程序中的两个调用具有未指定的行为。可能不满足 Derived1
的对齐要求或 Derived2
.即使满足了对齐要求,对exec
的调用很可能会违反 3.10/10 中的严格别名限制,因为您正在处理可能是 Wrapper<Base>
的对象表示形式的内容。就好像它是一个 Derived
.
用reinterpret_cast
写的事实上,asT<Base>(Wrapper<Base>&)
甚至有未定义的行为。自Wrapper<Base>
以来,当然满足了对齐要求。源自 Base
, 但实际上使用返回的 glvalue 访问内存只有在 Wrapper<Base>
的地址时才具有定义的行为与其Base
的地址相同子对象。如果 Wrapper<Base>
就是这种情况是标准布局,但其他对象布局未指定。
总结
该程序多次出现未定义的行为。正常工作的外观是实现选择的对象布局的产物。
关于c++ - 使用 reinterpret_cast 和 static_cast 模拟具有多态参数的模板中的协变和逆变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28810470/