返回无效的引用 [英] Returning an invalid reference
问题描述
有时候,当我在C ++中编程时,我希望对每个变量,如Javascript!有一个 undefined
值。
例如,当我为数组的out-of-bounds元素返回一个值时,返回一个 undefined
而不是抛出异常是有用的,或:
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; !!
}
};
另一个脏(在我看来)选项返回一个预定义变量的引用为坏 - 参考变量。我知道我们不能将 null
或类似的东西赋给一个引用变量。
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: 指针
推荐答案
在他的评论。它作为Boost libary的一部分。有关详情,请参见此页。
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.
修改 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&>();
}
};
用法:
MyArray<int>() array;
// fill array with data
optional<int&> result = array[0];
if (result) {
// item was found
} else {
// index out of bounds
}
这篇关于返回无效的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!