Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Boundary checking in operator[] #24

Closed
marton78 opened this issue Jul 11, 2016 · 1 comment
Closed

Boundary checking in operator[] #24

marton78 opened this issue Jul 11, 2016 · 1 comment

Comments

@marton78
Copy link

marton78 commented Jul 11, 2016

Hi,

I saw you removed boundary checking in operator[], but later you undid that change. What is your rationale of either adding or removing it?

My view is, that the general C++ philosophy of zero-cost abstractions and "don't pay for what you don't use" is violated by performing bounds checking when indexing. Indexing should be unchecked, if the user desires boundary checking behaviour, she can always opt-in by using the at() member function.

This is the general consensus in the STL, e.g. in std::vector and std::array.

What do you think?

Thanks,
Márton

@marton78 marton78 changed the title Boundary check of operator[] Boundary checking in operator[] Jul 11, 2016
@martinmoene
Copy link
Collaborator

martinmoene commented Jul 11, 2016

span is part of the GSL Bounds safety profile.

Quoting:

Bounds.1: Don't use pointer arithmetic. Use span instead.
Reason
Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. span is a bounds-checked, safe type for accessing arrays of data.

Microsoft's GSL indeed performs the check in:

#include <gsl.h>
#include <iostream>

int use( gsl::span<int> s, int i ) 
{
    return s[i];
}

int main()
{
    int arr[] = { 1, 2, 3, };

    try
    {
        (void) use( arr, 0 );
        (void) use( arr, 1 );
        (void) use( arr, 2 );
        (void) use( arr, 3 );
    }
    catch( std::exception const & e )
    {
        std::cout << "Error: " << e.what();
    }
}

Compile (g++ (GCC) 5.2.0) and run (M-GSL):

prompt> g++ -Wall -std=c++14 -DGSL_THROW_ON_CONTRACT_VIOLATION -I../../M-GSL/include -o main.exe main.cpp && main.exe
Error: GSL: Precondition failure at ../../M-GSL/include/span.h: 388

Compile (g++ (GCC) 5.2.0) and run (gsl-lite):

prompt> g++ -Wall -std=c++14 -DGSL_THROW_ON_CONTRACT_VIOLATION -I../../gsl-lite/include -o main.exe main.cpp && main.exe
Error: GSL: Precondition failure at ../../gsl-lite/include/gsl/gsl-lite.h: 835

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants