c++ - Pointer to unique_ptr - is this a loophole?
问题描述
It seems an easy way to circumvent a unique_ptr
is to use a pointer to the unique_ptr
object. And that's not difficult. So using the unique_ptr is sort of a gentleman's agreement and not really super enforced?
#include <iostream>
#include <memory>
using namespace std;
class Box {
public:
int num;
};
void update_box(unique_ptr<Box>* pu);
int main(){
unique_ptr<Box> b{new Box};
unique_ptr<Box>* u = &b;
update_box(u);
cout << b->num << endl; // Outputs 99.
return 0;
}
void update_box(unique_ptr<Box>* pu) {
(*pu)->num = 99;
}
解决方案
从某种意义上说,C++ 充满了君子协定。换句话说,这种语言让你有能力在脚下开枪。
没有什么可以阻止您获取 a 的地址std::unique_ptr
。如果您真的std::unique_ptr
觉得这很令人反感,那么您可以使用包含静态断言的函数继承并重载 address-of 运算符。
但即使你这样做了,你也可以用std::addressof
!
推荐阅读
- amcharts4 - 上午图表 4 LineSeries 图例颜色与图表颜色不匹配
- python - 使用linkGrabber从python中的谷歌搜索中获取'href'
- python - 指定数据类型时 Pandas 舍入不起作用?
- ios - Apple App Site Association 文件解析错误
- javascript - 如何编写一个函数以在单击删除时从购物车中删除一个项目
- powershell - 仅使用 Powershell 备份文件新文件
- c# - 30 秒后,信息窗口跳转到 WPF 中的登录窗口
- java - spring @Transactional 中途回滚
- javascript - create-react-native-app :术语“create-react-native-app”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称
- javascript - 如何检测 Excel Javascript 加载项范围内的合并单元格?