Constraint problem checking element std :: array inside const function

I get weird behavioral estimates by checking the std :: array element with mingw (gcc 4.7.0) with the following code

#include <iostream> #include <array> class testClass { std::array<int, 2> testArray; public: testClass(); void func() const; }; testClass::testClass() : testArray({{1, 2}}) { } void testClass::func() const { for (int i = 0; i < 2; ++i) std::cout << testArray.at(i) << '\n' << testArray[i] << '\n'; } int main() { testClass test; test.func(); } 

Exit

 0 1 0 2 

The error seems to be related to optimization, since it only occurs when compiling with -O , I tried the individual flags allowed by -O , but could not narrow it further. A problem with the non-const function also fixes the problem. Could this be a mistake, or am I missing something?

* change

Narrowed down, looks like an error in the const .at() version

 #include <iostream> #include <array> int main() { std::array<int, 2> const testArray = {1, 2}; for (int i = 0; i < 2; ++i) std::cout << testArray.at(i) << '\n' << testArray[i] << '\n'; } 

The same output as above was compiled using -std=c++11 -O using mingw 4.7.0 for Windows Xp sp3 and Windows 7 sp1.

* edit 2

Repeat the same conclusion

 #include <iostream> #include <array> int main() { typedef std::array<int, 2> Tarray; Tarray test = {1, 2}; for (int i = 0; i < 2; ++i) std::cout << const_cast<Tarray const*>(&test)->at(i) << '\n' << test.at(i) << '\n'; } 
+8
c ++ c ++ 11 mingw
source share
1 answer

This is part of the array header.

 #ifdef __EXCEPTIONS constexpr const_reference at(size_type __n) const { return __n < _Nm ? _M_instance[__n] : throw out_of_range(__N("array::at")); } #else const_reference at(size_type __n) const { if (__n >= _Nm) std::__throw_out_of_range(__N("array::at")); return _M_instance[__n]; } #endif 

Undef __EXCEPTIONS in the main file (or change #ifdef to #ifndef in the array) leads to the correct output. I don’t know if this is the right decision or not, but it works.

UPD: I change the code in the array header to

 #ifdef __EXCEPTIONS constexpr const_reference at(size_type __n) const { return __n < _Nm ? _M_instance[__n] : (throw out_of_range(__N("array::at"))), _M_instance[__n]; /*return __n < _Nm ? _M_instance[__n] : throw out_of_range(__N("array::at"));*/ } #else const_reference at(size_type __n) const { if (__n >= _Nm) std::__throw_out_of_range(__N("array::at")); return _M_instance[__n]; } #endif 

Now everything is working correctly

+5
source share

All Articles