我正在尝试实现更危险的 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>**
.我该如何解决它。
我在 Windows 8.1 上使用 Visual Studio 2017 社区
最佳答案
由于匿名 union ,您会收到该错误。由于 union 的成员被注入(inject)到周围的范围中,因此您有一个 TFrom* from
变量,它隐藏了引用参数 TFrom& from
。
所以你在初始化器中获取了一个指针的地址。因此整个双指针恶作剧。
除此之外,reinterpret_cast
已经够危险了,所以我觉得你让这个更糟糕的 Actor 阵容的工作是多余的。
关于c++ - 为什么拿一个引用的地址给我一个二级指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49217189/