How to initialize const elements

For example, I have two classes

class Foo; class Bar; class Foo { const Bar &m_bar; ... }; class Bar { const Foo &m_foo; ... }; 

Let foo be the foo object and bar object. Is there a way (normal or β€œhack”) to create / initialize foo and bar so that their members m_bar and m_foo will refer to each other (I mean foo.m_bar is bar and bar.m_foo is 'foo')?

It is allowed to add any elements to foo and bar to add parents to them, make them templates, etc.

+6
source share
2 answers

What is the relationship between foo and bar ? If they have external linkage, you can write something like:

 extern Foo foo; extern Bar bar; Foo foo( bar ); Bar bar( foo ); 

(I assume these are constructors that set a parameter reference.)

This assumes a namespace space and a static lifetime, of course (but an anonymous namespace is fine).

If they are members of a class, then there is no problem:

 class Together { Foo foo; Bar bar; public: Together() : foo( bar ), bar( foo ) {} }; 

If they are local variables (without binding), I don't think there is a solution.

EDIT:

Actually, local variables have a simple solution: just define a local class that has them as members and use it.

+6
source

This may not work if I understand your problem correctly, since you need Foo and vice versa to create an object panel. Instead, you should not use links other than a pointer. Where you can create both separatley objects and then set Bar to Foo and Foo to Bar.

 class Foo { public: Foo(); void setBar( const Bar* bar ){ _bar = bar; } private: const Bar* _bar; } // class Bar analog to Foo void xxx:something(void) { Foo* f = new Foo; Bar* b = nee Bar; f->setBar(b); b->setBar(f); ... } 
0
source

Source: https://habr.com/ru/post/953772/


All Articles