Make rvalues persist as pointers in a recursive class

64 Views Asked by At

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.

1

There are 1 best solutions below

0
Captain Giraffe On

You would probably like to have the concept of a List to supplement your Node. In combination with an initializer_list this can get quite neat.

Something like

#include <iostream>

struct ListNode {
    int data_;
    ListNode *child_;
    ListNode(int data, ListNode *child) : data_{data}, child_{child} {}
};

struct List{
    ListNode* head = nullptr;
    List(std::initializer_list<int> list){
        for(auto val:list){
            insert(val);
        }
    }
    void insert(int value){
        head = new ListNode(value, head);
    }
};

now you can create it with something like

int main() {
    List list = {3, 2, 1};
}

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.