Home > Blockchain >  How to resolve circular dependence in the following case?
How to resolve circular dependence in the following case?

Time:02-14

#include <iostream>
#include <set>

struct ContainerOfA;

struct StructA
{
  StructA(ContainerOfA* ptr) : m_b_ptr(ptr)
  {}

  void CleanMe()
  {
    m_b_ptr->RemoveStructA(this);
    delete this;
  }

  ContainerOfA* m_b_ptr;
};

struct ContainerOfA
{
  void RemoveStructA(StructA *a_ptr)
  {
    m_set_a.erase(a_ptr);
  }

  void RemoveAllStructA()
  {
    for (auto &iter : m_set_a) {
      delete iter;
    }
  }

  std::set<StructA*> m_set_a;
};

int main()
{
    return 0;
}

g (GCC) 10.2.1 20210130

test_me.cpp: In member function ‘void StructA::CleanMe()’:
test_me.cpp:13:12: error: invalid use of incomplete type ‘struct ContainerOfA’
   13 |     m_b_ptr->RemoveStructA(this);
      |            ^~
test_me.cpp:4:8: note: forward declaration of ‘struct ContainerOfA’
    4 | struct ContainerOfA;
      |        ^~~~~~~~~~~~

I ran into a circular dependency issue and the sample example is shown above.

Question> Is there a way that I can make it work?

Thank you

CodePudding user response:

Just move the problematic code to a point where the class is defined.

struct StructA
{
  // ...

  void CleanMe();
  // ...
};

struct ContainerOfA
{
  // ...
};

inline StructA::CleanMe()
{
  m_b_ptr->RemoveA(this);
}

By the way, that's a real code smell having an object know what container it's part of. You should try to architect it so that's not necessary.

  •  Tags:  
  • c
  • Related