No array bounds check when using auto

array1 is a pointer.

Useauto&& instead of auto there.


even though it has to be the same type

You’d think that. But if you check, you’ll find that they actually don’t have the same type:

std::cout << typeid(array1).name() << "\n";
std::cout << typeid(array2).name() << "\n";
P6Format
A3_6Format

Oops. The array returned by AllFormats decays to a pointer when assigned to an auto variable because that’s how the type deduction rules for auto work. Compare:

int& foo() {
    static int x = 42;
    return x;
}

auto x = foo(); // Type of `x` is `int`, not `int&`.

To prevent this, declare array1 as auto& or auto&&.

Tags:

C++

Clang

Clang++