Reputation: 1
I am taking a c++ class and one of the tasks is the following:
they gave us a main program and we had to write the code behind it. Here is that code:
vector<int> iv(4);
iv[3]=42;
cout << iv[3] << endl; // prints "42"
try {
cout << iv[1] << endl; // throw exception
}
catch (vector<int>::Uninitialized&){
cout << "Uninitialized vector element!" << endl;
}
return 0;
I've come up with this code for the vector template:
T* data;
unsigned int size;
public:
class Uninitialized{};
explicit vector(int size) {
data = new T[size];
this -> size = size;
for (unsigned i = 0; i < size; i++) {
data[i] = 0;
}
}
~vector() {
delete [] data;
}
T& operator[](int index) {
if (index >= size) {
abort();
}
return data[index];
}
friend ostream& operator<< (ostream& o, const T& t) {
if (t == 0)
throw Uninitialized();
else
return o << t;
}
However, the friend method is never called, so the exception is never thrown.
Upvotes: 0
Views: 100
Reputation: 18964
When your code runs iv[3] = 0
, which is outside the try
.. catch
, it will throw an exception because iv[3]
is zero at that point.
You need to tell when an assignment has happened to an element. I suspect your best bet is to return a proxy class from operator []
, which then has operators for assignment and converstion to T
.
Upvotes: 1
Reputation: 949
You're throwing at
iv[3]=42;
because at that point, data[3] == 0
.
Remember, even in your assignment you're calling operator[]
; it doesn't care (or even know) if you want the T&
for reading or writing.
You should approach this kind of problem (and, in general, problems where the code is simple enough and you know how to make the bug appear) by stepping through it with a debugger first. You would have caught this -- you'd immediately see that the exception isn't being thrown where you think it is.
Upvotes: 1