Reputation: 3493
I'm working on an assignment in school where we are supposed to make a constructor to our own List-class that takes an initialization list as an argument.
This is what I want to be able to do:
List ourList {1, 2, 3};
This is what I have so far:
List::List(std::initializer_list<int> il)
{
head_ = copy(il.begin(), il.end());
}
List_Node* List::copy(std::initializer_list<int>::iterator begin,
std::initializer_list<int>::iterator end)
{
if(begin == end)
return nullptr;
List_Node* new_list = new List_Node(*begin);
List_Node* node = copy(begin++, end);
new_list->next_ = node;
return new_list;
}
In my humble opinion, this should work great. However, when I try my initialization (List list {1,2,3};
) I get a seg-fault. Could someone please explain what it is I'm doing wrong here?
Upvotes: 0
Views: 113
Reputation: 171253
List_Node* node = copy(begin++, end);
This will call copy
again with the same arguments, recursing forever and never completing.
You should have been able to tell this by using a debugger to see where it crashed, and you would have seen that there were hundreds of calls to List::copy
, not the three calls you expected.
You want ++begin
not begin++
Upvotes: 6