为什么要拿参考的地址给我一个第二等级的指针

Why take the address of a reference give me a second rank pointer?

本文关键字:一个 指针 参考 地址 为什么      更新时间:2023-10-16

我正在尝试实现一个更危险的reinterpret_cast。代码打击似乎不起作用。

#include<iostream>
#include<memory>
using namespace std;
template<typename TTo, typename TFrom>
TTo& horrible_cast(TFrom& from) {
    static_assert(sizeof(TFrom) == sizeof(TTo), "");
    union {
        TFrom* from = &from;  // error cannot convert
                              // from 'std::unique_ptr<int,std::default_delete<_Ty>> **' 
                              // to 'std::unique_ptr<int,std::default_delete<_Ty>> *' 
        TTo* to;
    };
    return *to;
    // return *reinterpret_cast<TTo*>(&from); this one works fine.
}

int main() {
    unique_ptr<int> u{ new int(3) };
    auto x = horrible_cast<int*>(u);
}

TFrom&被推算为unique_ptr<int>&。但是当取它的地址时,它会给出一个unique_ptr<int>**.我该如何解决它。我在窗口 8.1 上使用 Visual Studio 2017 社区

由于匿名联合,您会收到该错误。由于联合的成员被注入到周围的作用域中,因此您有一个TFrom* from变量,该变量TFrom& from 隐藏引用参数。

因此,您正在初始化设定项中获取指针的地址。因此,整个双指针恶作剧。

除此之外,reinterpret_cast已经足够危险了,所以我觉得你让这个更糟糕的演员阵容的工作是多余的。