make_checked_array_iterator

创建可由其他算法使用的 checked_array_iterator

备注

该函数是标准 C++ 库的 Microsoft 扩展。使用该函数实现的代码不可移植到不支持该 Microsoft 扩展的 C++ 标准生成环境中。

template <class Iter>
  checked_array_iterator<Iter> 
    make_checked_array_iterator(
      Iter Ptr,
      size_t Size,
      size_t Index = 0
);

参数

  • Ptr
    指向目标数组的指针。

  • Size
    目标数组的大小。

  • Index
    数组的可选索引。

返回值

checked_array_iterator 的一个实例。

备注

make_checked_array_iterator 函数在 stdext 命名空间中定义。

此函数采用原始指针(此指针通常会导致有关边界溢出的问题),并将其包装在执行检查的 checked_array_iterator 类中。 由于此类标记为已检查,STL 不会对此发出警告。 有关详细信息和代码示例,请参阅经过检查的迭代器

示例

在下面的示例中,将创建一个 vector,并在其中填充 10 项。 矢量内容通过复制算法复制到数组,随后使用 make_checked_array_iterator 指定目标。 这在有意违反边界后进行,因此将触发调试断言失败。

// make_checked_array_iterator.cpp
// compile with: /EHsc /W4 /MTd

#include <algorithm>
#include <iterator> // stdext::make_checked_array_iterator
#include <memory> // std::make_unique
#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }

    cout << endl;
}

int main()
{
    const size_t dest_size = 10;
    // Old-school but not exception safe, favor make_unique<int[]>
    // int* dest = new int[dest_size];
    unique_ptr<int[]> updest = make_unique<int[]>(dest_size);
    int* dest = updest.get(); // get a raw pointer for the demo

    vector<int> v;

    for (int i = 0; i < dest_size; ++i) {
        v.push_back(i);
    }
    print("vector v: ", v);

    copy(v.begin(), v.end(), stdext::make_checked_array_iterator(dest, dest_size));

    cout << "int array dest: ";
    for (int i = 0; i < dest_size; ++i) {
        cout << dest[i] << " ";
    }
    cout << endl;

    // Add another element to the vector to force an overrun.
    v.push_back(10);
    // The next line causes a debug assertion when it executes.
    copy(v.begin(), v.end(), stdext::make_checked_array_iterator(dest, dest_size));
}

输出

vector v: 0 1 2 3 4 5 6 7 8 9
int array dest: 0 1 2 3 4 5 6 7 8 9

要求

标头:<iterator>

**命名空间:**stdext

请参见

参考

标准模板库