微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

内存管理 - 删除保留指向同一向量前一个元素的指针的对象向量

如何解决内存管理 - 删除保留指向同一向量前一个元素的指针的对象向量

刚接触 C++。

假设我有一个 std::vector<Foo*> foos;Foo

// This is a virtual class in my case.
class Foo {
private:
  Foo* m_prevIoUs_foo { nullptr };
public:
  // Should this class have a destructor destroying its m_prevIoUs_foo?
  // IMO this seems incorrect,since a removal of 
  // Foo from Bar would delete a Foo I still want to retain,I guess?

  // Called by Bar's constructor,necessary for my use case.
  void set_prevIoUs(Foo* prevIoUs_foo) { m_prevIoUs_foo = prevIoUs_foo; };

  const bool prevIoUs_is_valid() const { return m_prevIoUs_foo != nullptr; };
};

和拥有该向量的 Bar

class Bar {
private:
  std::vector<Foo*> m_foos;
public:
 ~Bar() {
   // What do I do here?

   // My idea 1:
   for (auto p_foo : m_foos) {
     if (p_foo->prevIoUs_is_valid()) {
       delete p_foo->get_prevIoUs();
     } else { // PrevIoUs pointer is already nullptr,only delete pointer
       delete p_foo;
     }
   }

   // My idea 2:
   for (auto p_foo : m_foos) {
     delete p_foo;
   }

   // My idea 3: essentially the same as idea 1 but checking for index 0
   // as the only case where we delete the pointer.
 }
}

编辑:此向量如何使用 4 个元素的示例:

vector[0] = Foo with m_prevIoUs_foo = nullptr
vector[1] = Foo with m_prevIoUs_foo = &vector[0];
vector[2] = Foo with m_prevIoUs_foo = &vector[1];
vector[3] = Foo with m_prevIoUs_foo = &vector[2];

我的猜测是所有这些都是不正确的,因为无论我如何删除这些指针,它们都会在“下一个”Foo 中失效,即 Foo 拥有现在删除的指针。

编辑:我仍然在训练轮子上,我已经阅读了有关智能指针的内容,但是,我不理解它们,并且我认为在使用更智能的抽象之前我应该​​了解指针管理。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。