I have a simple linked list node class which I can use to create a list 1->2->3 like so:
struct ListNode {
int data_;
ListNode *child_;
ListNode(int data, ListNode *child) : data_{data}, child_{child} {}
};
ListNode node3(3, &node4);
ListNode node2(2, &node3);
ListNode head(1, &node2);
I want to make this construction less verbose by adding a new constructor, allowing something to the effect of:
ListNode head(1, (2, (3, nullptr)));
Essentially, I'd like the temporary objects created in the constructor to persist so I can point to them. How can I achieve this?
I've found an answer to a similar question here but I this doesn't handle the recursive structure in my class definition. I've been looking at move semantics but can't understand how to make it work with child being a pointer type.
You would probably like to have the concept of a List to supplement your Node. In combination with an
initializer_listthis can get quite neat.Something like
now you can create it with something like
See https://godbolt.org/z/sn6orf5h9
Now, there are plenty of improvements to be made here of course, some mentioned in the comments. But that was not what you were asking for.