c++ - 在 C++ 中 decltype 取消引用的指针

标签 c++ pointers decltype

有人可以向我解释为什么我不能按照以下方式做某事吗:

int* b = new int(5);
int* c = new decltype(*b)(5);

cout << *c << endl;

这将引发 C464“int &”:无法使用“new”分配引用。我将如何执行这样的操作?我需要的是我发送的变量的取消引用基类型。

这虽然有效

int* b = new int(5);
int** a = new int*(b);

decltype(*a) c = *a;
cout << *c<< endl;

我明白上面的代码是如何工作的,但我如何使用 new 执行类似的操作?

最佳答案

解引用运算符 *返回一个不能使用 new 分配的引用.相反,您可以使用 std::remove_pointer <type_traits>

int* b = new int(5);
int* c = new std::remove_pointer<decltype(b)>::type(5);    
std::cout << *c << std::endl;

关于c++ - 在 C++ 中 decltype 取消引用的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34231547/

相关文章:

c - 更新函数中的结构数组并将其作为参数传递给其他函数

c - 无法预测以下程序的输出

c++ - 在已打开的文件上删除ItemAtPath

c++ - 模板类中的 is_foo 结构

c++ - 复制构造函数定义和声明区别?

c++ - OpenCV 中的奇怪数组错误

c++ - 用 C++ 制作游戏训练器?

visual-c++ - 获取模板lambda参数的返回值,如何简化代码?

c++11 - 对成员函数返回类型使用 decltype 时,声明顺序很重要

c++ - auto、decltype(auto) 和尾随返回类型