Note that there are some explanatory texts on larger screens.

plurals
  1. POInitializing mutually-referencing objects
    text
    copied!<p>Consider the following pair of mutually referencing types:</p> <pre><code>struct A; struct B { A&amp; a; }; struct A { B&amp; b; }; </code></pre> <p>This can be initialized with aggregate initialization in GCC, Clang, Intel, MSVC, but not SunPro which insists that user-defined ctors are required.</p> <pre><code>struct {A first; B second;} pair = {pair.second, pair.first}; </code></pre> <p>Is this initialization legal? </p> <p>slightly more elaborate demo: <a href="http://ideone.com/P4XFw" rel="nofollow noreferrer">http://ideone.com/P4XFw</a></p> <p>Now, heeding Sun's warning, what about classes with user-defined constructors? The following works in GCC, clang, Intel, SunPro, and MSVC, but is it legal?</p> <pre><code>struct A; struct B { A&amp; ref; B(A&amp; a) : ref(a) {} }; struct A { B&amp; ref; A(B&amp; b) : ref(b) {} }; struct {B first; A second;} pair = {pair.second, pair.first}; </code></pre> <p>demo: <a href="http://ideone.com/QQEpA" rel="nofollow noreferrer">http://ideone.com/QQEpA</a></p> <p>And finally, what if the container is not trivial either, e.g. (works in G++, Intel, Clang (with warnings), but not MSVC ("pair" unknown in initializer) or SunPro ("pair is not a structure")</p> <pre><code>std::pair&lt;A, B&gt; pair(pair.second, pair.first); </code></pre> <p>From what I can see, <code>§3.8[basic.life]/6</code> forbids access to a non-static data member before lifetime begins, but is lvalue evaluation of pair.second "access" to second? If it is, then are all three initializations illegal? Also, <code>§8.3.2[dcl.ref]/5</code> says "reference shall be initialized to refer to a valid object" which probably makes all three illegal as well, but perhaps I'm missing something and the compilers accept this for a reason.</p> <p>PS: I realize these classes are not practical in any way, hence the language-lawyer tag. Related and marginally more practical old discussion here: <a href="https://stackoverflow.com/questions/1329223/circular-reference-in-c-without-pointers/1329257#1329257">Circular reference in C++ without pointers</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload