首页 > 解决方案 > 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++unique-ptr

解决方案


从某种意义上说,C++ 充满了君子协定。换句话说,这种语言让你有能力在脚下开枪。

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

但即使你这样做了,你也可以用std::addressof!


推荐阅读