gpt4 book ai didi

c++ - 指向 unique_ptr 的指针——这是一个漏洞吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:09:12 26 4
gpt4 key购买 nike

似乎绕过 unique_ptr 的一种简单方法是使用指向 unique_ptr 对象的指针。这并不难。所以使用 unique_ptr 是一种君子协定,并没有真正 super 强制执行?

#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++ 充满了君子协定。换句话说,语言让你有能力搬起石头砸自己的脚。

没有什么可以阻止您获取 std::unique_ptr 的地址。如果您真的觉得这令人反感,那么您可以从 std::unique_ptr 继承并使用包含静态断言的函数重载 address-of 运算符。

但即使您这样做了,您也可以使用 std::addressof 来规避它!

关于c++ - 指向 unique_ptr 的指针——这是一个漏洞吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52496628/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com