简体   繁体   中英

Make rvalues persist as pointers in a recursive class

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_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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM