When compiling with _SECURE_SCL 1, a runtime error will occur if you attempt to access an element outside the bounds of the container with the indexing operator of certain classes (see above).
// checked_iterators_1.cpp
// compile with: /EHsc
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v;
v.push_back(67);
int i = v[0];
cout << i << endl;
try {
i = v[1];
}
catch (std::out_of_range) {
cout << "invalid container access" << endl;
}
}; Output
67
invalid container access
When compiling with _SECURE_SCL 1, a runtime error will occur if you attempt to access an element with front or back of certain classes (see above), when the container is empty.
// checked_iterators_2.cpp
// compile with: /EHsc
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
#include <vector>
#include <iostream>
int main() {
using namespace std;
vector <int> v1;
try {
int& i = v1.front();
}
catch (std::out_of_range) {
cout << "vector is empty!!" << endl;
}
} Output
vector is empty!!
When compiling with _SECURE_SCL 1, the compiler enforces the use of a checked iterator on standard algorithms that also have checked and unchecked versions (see above).
// checked_iterators_3.cpp
// compile with: /EHsc /W3
#define _SECURE_SCL 1
#include <algorithm>
#include <iostream>
using namespace std;
using namespace stdext;
int main() {
int a[] = { 1, 2, 3 };
int *b = new int[10];
int c[10];
copy(a, a + 3, b); // C4996 unchecked iterator
copy(a, a + 3, checked_array_iterator<int*>(c, _countof(c))); // OK
delete[] b;
} The following example sets _SECURE_SCL to 0, thus disabling checked iterators. With checked iterators disabled, you must take extra caution to ensure you do not iterate beyond the bounds of your container.
// checked_iterators_4.cpp
// compile with: /EHsc
#define _SECURE_SCL 0
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v;
v.push_back(67);
int i = v[0];
cout << i << endl;
}; Output
67