c++ - 使用 reinterpret_cast 和 static_cast 模拟具有多态参数的模板中的协变和逆变?

标签 c++ templates polymorphism c++14 reinterpret-cast

假设我有一个简单的多态继承:

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来自 BaseWrapper<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,” where B is a class type, can be cast to type “reference to cv2 D,” where D is a class derived (Clause 10) from B, if a valid standard conversion from “pointer to D” to “pointer to B” exists (4.10), cv2 is the same cv-qualification as, or greater cv-qualification than, cv1, and B is neither a virtual base class of D nor a base class of a virtual base class of D. The result has type “cv2 D.” An xvalue of type “cv1 B” may be cast to type “rvalue reference to cv2 D” with the same constraints as for an lvalue of type “cv1 B.” If the object of type “cv1 B” is actually a subobject of an object of type D, the result refers to the enclosing object of type D. 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 cv T”, the result is static_cast<cv T*>(static_cast<cv void*>(v)). Converting a prvalue of type “pointer to T1” to the type “pointer to T2” (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) 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 to T2” if an expression of type “pointer to T1” can be explicitly converted to the type “pointer to T2” using a reinterpret_cast. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference cast reinterpret_cast<T&>(x) has the same effect as the conversion *reinterpret_cast<T*>(&x) with the built-in & and * operators (and similarly for reinterpret_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 type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (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 expression e 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,” where T is an object type, can be converted to a prvalue of type “pointer to cv void”. The result of converting a non-null pointer value of a pointer to object type to a “pointer to cv void” 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*2 T,” where T 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 address A of a byte in memory and A satisfies the alignment requirement of T, 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 cv void” 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/

相关文章:

java - 多态性如何用于内部类?

C++ 多态类、虚函数和性能转换

c++ - Linux 线程傻瓜。有人可以解释一下 linux 中多线程库之间的区别吗?

c++ - "No Matching Constructor"尝试实例化模板类的对象时出错

c++ - 将抽象类(仅限纯虚函数)的继承/派生限制在某个类

c++ - 在子类中调用基类的模板函数是否合法?

c++ - 为什么在 C++ 中给定指向基类的指针时不调用派生类对象的重载函数?

c# - 调用 C++ 函数时尝试读取/写入 protected 内存错误

c++ - 如何将字符串数组从 C 和 Fortran 传递给 Fortran?

c++ - C++ 中的抽象仿函数