简体   繁体   中英

bound check for iterator in Release mode (c++)

I intentionally made iterator to exceed the size of std::vector like,

for (std::vector <Face>::iterator f = face.begin();
          f!=face.end()+5;
               ++f)
{
    // here I try to access (*f).P
    // note that I added 5 to the face.end()
}

I did not face any error neither during compiling and run-time. How can I prevent that?

If you want checked access to vector elements, you may use the at function which throws std::out_of_range exception in case of boundary violation. Example:

for (std::vector<Face>::size_type i = 0;
          i != face.size()+5;
               ++i)
{
    face.at(i).f();
}

The standard doesn't specify any checked iterators. The wording in the standard is that access to an invalid iterator results in undefined behavior. But many implementations provide checked iterators. If portability is not a concern, you may use one of those checked iterators. For example, in MSVC Debug mode, vector<T>::iterator is a checked iterator. In Release mode, however, it's just a typedef for T*

What C++ compiler are you using? VC10 (ie the C++ compiler in VS2010) in debug build correctly identifies the problem:

// Compile with:
// cl /EHsc /W4 /nologo /D_DEBUG /MDd test.cpp


#include <iostream>
#include <string>
#include <vector>


class Face
{
public:
    std::string Name;

    explicit Face(const std::string & name)
      : Name(name)
    {}
};


int main()
{
    std::vector<Face> faces;
    faces.push_back( Face("Connie") );
    faces.push_back( Face("John") );

    for (
        std::vector <Face>::iterator f = faces.begin();
        f != faces.end() + 5;
        ++f)
    {
        std::cout << f->Name << std::endl;
    }

    return 0;
}

When executing the resulting .exe, an error dialog box is showed with the following error message:

Expression: vector iterator + offset out of range

For a release version of the standard C++ library you won't get build-in bounds checking on your iterators (or other operations which may be unchecked) because it would be comparatively slow. However, this doesn't mean that you need to compile in debug mode: as far as I understand the libstdc++ debug mode it can be used when compiling with compiler optimizations turned on. I would suspect that this true for other checked STL implementations because the checked code is typically just guided by setting up some macros appropriately. To do this you'll need to find the appropriate macro settings and set them up appropriately with whatever you use to build your code.

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