简体   繁体   English

如何使用C ++智能指针复制变化的指针?

[英]How do you replicate a changing pointer with C++ smart pointer?

struct A {
   int val;
};
struct B {
    int val2;
    A* ptr = nullptr;
};

int main() {
    A a1, a2;
    B b;
    if (...) { B.ptr = &a1; } else { B.ptr = &a2; }
    return 0;
}

How can ptr be represented with a smart ptr? 如何用智能PTR表示PTR? It doesn't own but needs to access the objects a1 and a2. 它不是所有者,但需要访问对象a1和a2。 B 'uses' only one of a1 or a2, which later may toggle. B仅“使用” a1或a2中的一个,以后可能会切换。

Changing ptr doesn't mean a1 or a2 should be deleted ofcourse. 更改ptr并不意味着当然要删除a1或a2。 So, unique_ptr.reset() is not a solution. 因此,unique_ptr.reset()不是解决方案。

In this particular case you don't need a smart pointer in order to delete a1 or a2. 在这种情况下,您不需要智能指针即可删除a1或a2。

So it would seem that a smart pointer is not needed at all... 因此似乎根本不需要智能指针...

Unless you wanted some special cleanup code to be executed on only one of the objects when b goes out of scope. 除非您希望当b超出范围时仅对其中一个对象执行一些特殊的清除代码。

In which case it would look something like this: 在这种情况下,它将看起来像这样:

struct A {
   int val = 0;
};

struct cleanup_A {
  void operator()(A* pa) const {
    if (pa) { my_cleanup_action(*pa); }
  }
};

struct B {
  using special_A_ptr = std::unique_ptr<A, cleanup_A>;
  int val2 = 0;
  special_A_ptr ptr = { nullptr, cleanup_A() };
};

int main() {
  A a1,a2;
  B b;
  if (...) { b.ptr.reset(&a1); } else { b.ptr.reset(&a2); }
  return 0;
}

Of course in such cases of non-standard use, all the usual warnings apply... 当然,在这种非标准使用的情况下,所有常规警告都适用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM