Returning an invalid reference
c++
Solution
You can use boost::optional as @chris mentioned in his comment. It comes as a part of Boost libary. See this page for more details.
Modified `MyArray` class:
template <typename T, int SIZE>
class MyArray
{
T arr[SIZE];
public:
optional<T&> operator[](int i)
{
if (i >=0 && i < SIZE)
return optional<T&>(arr[i]);
else
return optional<T&>();
}
};
Usage:
MyArray<int>() array;
// fill array with data
optional<int&> result = array[0];
if (result) {
// item was found
} else {
// index out of bounds
}
Problem
Sometimes when I'm programming in C++ I wish there was an `undefined` value for every variable something like Javascript!. For example when I'm returning a value for out-of-bounds element of an array, it was useful to return an `undefined` instead of throwing an exception, or: ``` template <typename T, int SIZE> class MyArray { T arr[SIZE]; static T badref; public: T &operator[](int i) { if (i >=0 && i < SIZE) return arr[i]; else throw std::string("OUT-OF-BOUNDS"); // or: return badref; !! } }; ``` Another dirty(In my opinion) option is returning a reference of a pre-defind variable as a bad-reference variable. I know we can not assign `null` or something like that to a reference variable. Is there an another well formed pattern to return a reference where caller has the ability to find out the returned value is not valid? EDIT: I'm not mean a `pointer`