为什么 C++ 不支持基于范围的动态数组循环?也就是说,像这样:
int* array = new int[len];
for[] (int i : array) {};
我刚刚发明了 for[]
语句来与 new[]
和 delete[]
押韵。据我了解,运行时具有可用数组的大小(否则 delete[]
无法工作),因此理论上,基于范围的 for 循环也可以工作。什么原因导致它无法正常工作?
最佳答案
What is the reason that it's not made to work?
基于范围的循环,如
for(auto a : y) {
// ...
}
只是下面表达式的语法糖
auto endit = std::end(y);
for(auto it = std::begin(y); it != endit; ++it) {
auto a = *it;
// ...
}
由于 std::begin()
和 std::end()
不能与普通指针一起使用,因此不能与分配的指针一起使用新[]
.
As far as I understand, the runtime has the size of the array available (otherwise
delete[]
could not work)
delete[]
如何跟踪使用 new[]
分配的内存块(不一定与用户指定的大小相同) , 是完全不同的东西,编译器很可能甚至不知道它是如何实现的。
关于c++ - 为什么 C++ 不支持动态数组的基于范围的 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47363608/