In article <>,
cppaddict <> wrote:
>Hi,
>
>Is it considered bad form to have the subscript operator return a
>const reference variable? If not, what is the proper way to do it?
>My question was prompted by the code below, my problematic attempt to
>implement a subscript operator that returns a const reference. The
>dubious code is marked at the end.
>
><code>
>
>//MyClass is a large class we don't want to copy alot
>//MyClass has a "char getChar()" function
>class MyClass;
>
>class SubscriptTest {
> private:
> std::vector<MyClass> _vect;
> public:
> SubscriptTest() {};
> void addObj(MyClass mc) {_vect.push_back(mc);}
> const MyClass& operator[] (char ch) const {return
>lookUpByChar(ch);}
>};
>
>const MyClass& SubscriptTest::lookUpByChar(char ch) const {
> for (unsigned i=0; i<_vect.size(); i++) {
> if (_vect[i].getChar() == ch)
> return i;
> }
>
> //PROBLEM IS HERE
> return *(new MyClass); //return value here needed to compile
>}
>
></code>
>
>The problem is what to return when the lookup fails. Creating a
>default value via new, as I do above, seems wrong -- it wastes memory
>and requires tracking the objects created and then destroying them in
>Subscript's destructor.
>
>Another option would be to create the default value as static variable
>inside the lookUpByChar function or as a member variable of
>SubscriptTest, and have the function always return a reference to
>that. That seems reasonable to me, but I still wasn't sure.
>
>Does anyone have any thoughts/suggestions?
The const version and the non-const version of op[] should do the same
thing if the item isn't in the container.
You have a few choices, declare the behavior undefined (thats how op[]
is defined in vector,) insert an element (the way op[] works in map,) or
throw an exception (like vector::at does.)
What is best for the code that uses your container?
|