I'm overloading the subscript operator for the first time and I'm having troubles in returning a reference value.
I followed the rules of thumb from a post in c++faq tag, but there's something I'm missing.
const T& operator[](int index) const {
if ((index < 0) || (index > size)) {
// provide exception handling for this error
std::cout << "Error! Index out of bound." << std::endl;
std::exit(0);
} else {
Block* b = head;
while (b) {
if (b->position == index)
return *b->data;
b = b->next;
}
}
}
I implemented them in both variants: with const return value and const function (as above), and without (that is identical except for the two const keywords).
The problem is that when I run the test main, it simply crashes. I thought that the bug was in the return *b->data; statement, but I can't figure neither which it could be nor if I'm wrong and there are other errors.
Any ideas?
Thanks in advance.
(index > size)should be(index >= size)(or the more "visual"(size <= index)), because I guess that the valid range forindexis[0, size-1](i.e.[0, size)). Second, what if the execution never meets the condition(b->position == index)and exits the loop whenbbecomes null? Nothing will be returned by the function and that's undefined behavior, you should handle that error case too.indexthere's supposed to exist an equalpositionin aBlockof your (what seems to be a) linked-list) I suppose that you can put an assertion (or print an error and exit like above) after thewhilebody (or just before the end of the function body). After you do that, plus the fix from my first comment, does your program still crash? and/or does it print some error message?std::vector? There's so much to say about your pastebin (BTW you don't show yourmain)... A lot of pointers (with anewbut nodelete);headis left uninitialized withArray's default constructor (probable cause of crash if you useheadafterwards);Block's constructor wants aT*pointer but you pass it aTvalue (I thought it wouldn't compile but e.g. withArray<int>it passesint()i.e.0which is convertible to a (null) pointer, other probable cause of crash if you try*data); copy & destruction aren't handled --running out of characters