为什么要拿参考的地址给我一个第二等级的指针
Why take the address of a reference give me a second rank pointer?
我正在尝试实现一个更危险的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
已经足够危险了,所以我觉得你让这个更糟糕的演员阵容的工作是多余的。
相关文章:
- 修改函数中的指针(将另一个指针作为参数传递)
- 将指针分配给另一个指针时会发生什么情况?
- C++将一个指针分配给另一个指针时执行的类型检查
- 更改一个指针后更改乘法对象
- 从另一个指针指向函数的指针
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C:试图将指针值复制到另一个指针中,得到可修改的左值错误
- C++ typedef 函数指针,并在一个语句中声明一个指针
- 一个对象的两个指针.删除了一个指针,对象仍然存在
- 如何获得GUID编码器,如果我在IMFTransform上有一个指针?
- 我不明白我的错误需要返回一个指针数组
- 使用 SFINAE 测试是否可以将一个指针类型static_cast到另一个指针类型
- 将指针分配给另一个指针时会发生什么情况?
- 如何保存指针地址,以便另一个指针可以继续处理它
- 为什么 std::span 是一个指针 + 大小而不是两个迭代器
- 类的成员应该是一个指针
- 隐式指针变量,在自动定义中具有另一个指针变量
- 利用双重链接列表中的下一个指针
- 你能把一个指针投射到数组中吗?