C
cppaddict
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.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?
Thanks,
cpp
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.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?
Thanks,
cpp