[英]C++11 range-based for exceptional error
我一直在嘗試學習 The Revised C++11,在嘗試使用基於范圍的for
auto
和nullptr
程序時,出現錯誤:程序在接受數組的第一個元素后退出。
#include<iostream>
auto *Alloc(auto *p, int size) {
if (p != nullptr)
delete[]p;
p = new auto[size];
return p;
}
int main() {
int *P = nullptr;
Alloc(P, 5);
for (auto &X : P)
std::cin >> X;
for (auto X : P)
std::cout << X;
std::cin.ignore(5);
delete[]P;
return 0;
}
P 不是數組。 它被定義為pointer.P
int *P=nullptr;
指針沒有關於它們是指向單獨的單個對象還是指向序列的第一個對象的信息。 對於在基於范圍的 for 語句中隱式使用的指針,沒有函數begin()
和end()
。
考慮到,而不是
int *P = nullptr;
Alloc(P, 5);
你必須寫
int *P = nullptr;
P = Alloc(P, 5);
否則 P 仍將等於 nullptr。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.