c++ - 为什么 C++ 不支持动态数组的基于范围的 for 循环?

标签 c++

为什么 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/

相关文章:

c++ - if (cin >> x) - 你为什么可以使用那个条件?

c++ - 在 C++ 中编译复数类时出错

c++ - 如何沿一定体积绘制斜半球?

c++ - 在 C/C++ 中求和 bool 值

c++ - 如何将模板类型(std::array 或 std::vector)传递给模板参数

c++ - 指向非静态数据成员的指针在 VS2015 Update 2 中不正确

c++ - 模板特化和DLL:Visual Studio与(GCC/Clang)

c++ - GCC 如何从静态库导出函数

c++ - 有没有办法从基类函数参数中推导出模板参数?

c++ - 运行时类型比较