C++避免vector索引超出范围

描述:

该类通过重载operator[]来提供更安全的访问方式
重载operator[],并使用了std::enable_if和std::is_trivially_default_constructible来限制只有在T是默认构造的类型时才生效。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
template<typename T>
class VectorSafety : public std::vector<T>
{
public:
auto operator[](size_t i) const
-> std::enable_if_t<std::is_trivially_default_constructible<T>::value, T>
{
if (i < this->size())
{
return this->std::vector<T>::operator[](i);
}
else
{
// 可以根据需求抛出异常或返回一个特殊值
//throw std::out_of_range("VectorSafety index out of range");
LogErr("VectorSafety index out of range");
}
// 返回默认构造的元素
return T();
}

auto operator[](size_t i)
-> std::enable_if_t<std::is_trivially_default_constructible<T>::value, const T&>
{
if (i < this->size())
{
return this->std::vector<T>::operator[](i);
}
else
{
// 可以根据需求抛出异常或返回一个特殊值
//throw std::out_of_range("VectorSafety index out of range");
LogErr("VectorSafety index out of range");
}

if (this->empty())
{
// 插入默认构造的元素
this->emplace_back();
return this->back();
}
// 返回对第一个元素的引用
return this->front();
}
};

注意:

VectorSafety类的实例化要求T类型必须满足可默认构造的条件。否则,在编译时将会产生错误。