Re: Returning Nulls in Templates
On Mar 21, 4:00 pm, Ruben Safir <ru...@mrbrklyn.com> wrote:
On Mon, 21 Mar 2011 01:06:22 -0700, Goran wrote:
On Mar 20, 6:37 am, Ruben Safir <ru...@mrbrklyn.com> wrote:
[...]
What I learned here though, and which isn't readily apparent from reading
the texts, is that there is no true way to implement the behavior of a
native array.
I suspect there is, but I don't think anyone would want to.
In a native array:
int a[10]= {101,102,103,104,105,106,107,108,109};
int tmp;
tmp = a[3]; // passed by value
std::cout << tmp << end; // output 104
std::cout << a[3] << end; // output 104
tmp = 200;
std::cout << tmp << end; // output 200
std::cout << a[3] << end // output 104
a[3] = 500; //operator[]() is naively now in C++ equiv of pass by
//reference mode
std::cout << tmp << end; // output is STILL 200
std::cout << a[3] << end // output is not 500
Have you tried? Say by using std::vector<int> instead of int[]?
Or by writing your own vector class? In all cases, operator[]
returns a reference, and is overloaded on const.
Usually, when for a "no return value" case, operator[] is
implemented in two ways:
* proclaim undefined behavior (that is, crash) * throw an exception.
I'm coming to appreciate this more and more. I'm not that
happy with it, but that doesn't make me a better C++
programmer.
That's more or less part of the definition of []. Undefined
behavior if your index is out of bounds. Why should a user
defined class be any different. (I know, std::map is. One
could argue that that is a design error.)
Returning "error" value, that you seem to want to do, is quite unusual.
I don't think anyone here would agree with this course of action (in
general, but context trumps all, and one could probably think of a
context where "err" would do better). Sure, there's no crash (good), and
there's no exception (perhaps good), but it requires the caller either
to check for err after each call, either or to account for err in
general. That's too complicated for such a simple thing.
I might agree, but a lot of standard programming includes checking for
errors and I was taught such defense coding when I learned C programming
and in a few other languages.
In C++, one standard solution for things like out of bounds
accesses is an assert.
--
James Kanze