0

I have the following classes

class a {
        std::shared_ptr<b> b_ref;
    public:
        a(std::shared_ptr<b> b_ref) : b_ref(b_ref) {}
};

class b {
        std::shared_ptr<a> a_ref;
    public:
        b(std::shared_ptr<a> a_ref) : a_ref(a_ref) {}
};

Now I want to create two objects that reference each other is there any way to do this? I think with c-style pointers I could achieve this. Does it work with shared pointers as well? I tried the reset() and swap() methods without any success.

std::shared_ptr<a> a_ref;
std::shared_ptr<b> b_ref;

a_ref = std::make_shared<a>(b_ref);
b_ref = std::make_shared<b>(a_ref);

Did not work.

curiousguy
  • 8,038
  • 2
  • 40
  • 58
eclipse
  • 2,831
  • 3
  • 26
  • 34
  • Replace one shared_ptr member by a weak_ptr (or plain pointer) –  Aug 18 '15 at 16:01
  • What is the justification of this question? – curiousguy Aug 18 '15 at 16:10
  • @curiousguy There is no way to construct two classes referencing each other (a chicken and egg) –  Aug 18 '15 at 16:49
  • @DieterLücking Yes, as long as the member pointer is constant, there is no solution. How would a weak ref help? – curiousguy Aug 18 '15 at 16:51
  • 3
    @curiousguy That question is an XY-question: http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem –  Aug 18 '15 at 17:00

2 Answers2

9

Create one object first. Then the other. Set any pointers that haven't been set. That's it. Note that these circularly referring objects won't be freed automatically when there are no more external references to them: the cyclic dependency needs to be broken very explicitly.


Where there are circular dependencies, direct use of smart pointers is usually not an optimal solution. Do consider other designs.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
-1

It is easy to see that the problem as stated has no solution, as you can only create one of one the class instance at a time.

Jashaszun
  • 9,207
  • 3
  • 29
  • 57
curiousguy
  • 8,038
  • 2
  • 40
  • 58