简体   繁体   中英

Visual Studio checked iterator not throwing exceptions

I have this code:

#ifdef _DEBUG
#define _SECURE_SCL 1
#define _SECURE_SCL_THROWS 1
#else
#define _SECURE_SCL 0
#define _SECURE_SCL_THROWS 0
#endif

#include <iostream>
#include <vector>


using namespace std;




int main()
{
    vector <int> v1;
    v1.push_back(33);

    vector <int>::iterator it1 = v1.begin();

    try 
    {
        it1++;

        it1++;
    }
    catch (...) 
    {
        cout << "vector is empty!!" << endl;
    }

    return 0;
}

A pretty simple one: I try to go past-the-boundary and I want the exception to be caught. However the program simply crashes with a "Debug Assertion Failed!" on the second increment, why is that?

The example was taken from http://msdn.microsoft.com/en-us/library/aa985965(v=vs.100).aspx and I just added the macros to set the checked iterators on. I'm in debug mode, /EHsc is on and so is /MDd

You left the most important part out of your question -- the #include lines.

You need to put those macros ABOVE the #include lines. If you're using precompiled headers, you need to put them in the precompiled header.

Because the code in your question is not complete, I can't tell if you've done this right. I suspect you haven't, so I'm offering this as an answer.

The new version of Visual C++'s library (bundled in Visual Studio 2010) doesn't support throwing exceptions from checked iterators. See http://wishmesh.com/2010/04/it-seems-that-_secure_scl_throws-is-deprecated-in-visual-studio-c-2010/

A checked iterator refers to an iterator that will throw an exception or call invalid_parameter if you attempt to move past the boundaries of the container.

Your example code isn't moving an iterator, so I don't think it makes sense that anything would be thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM