The following program attempts to create a tree of nodes consisting of references to std::deque elements.
#include <deque>
struct Node;
using Pool = std::deque<Node>;
struct Node
{
Node(int d, Pool& pool)
: level{d}
, l{d > 0 ? pool.emplace_back(d - 1, pool) : *this}
, r{d > 0 ? pool.emplace_back(d - 1, pool) : *this}
{
}
int level;
const Node& l;
const Node& r;
int check() const
{
if(!(&l == this))
return l.check() + 1 + r.check();
else
return 1;
}
};
int main()
{
int depth{2};
Pool pool;
Node c(depth, pool);
return c.check()==7 ? 0 : 1;
}
It creates the correct number of elements, but not all references are initialized to the emplaced elements and the level variable is not set for levels higher than 0.
Finally, program fails due to this being a nullptr when the check() function is executed.
How can the references be correctly initialized?