C ++ 11基于范围的特殊错误

时间:2014-03-23 21:44:03

标签: c++ c++11

我一直在尝试学习修订版的C ++ 11,同时尝试使用 autonullptr使用基于范围的for,我有一个错误:程序退出后 接受数组的第一个元素。

#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;
}

1 个答案:

答案 0 :(得分:1)

P不是数组。它被定义为pointer.P

int *P=nullptr;

指针没有关于它们是指向单独的单个对象还是指向序列的第一个对象的信息。对于在基于语句的范围中隐式使用的指针,没有函数begin()end()

考虑到而不是

int *P = nullptr;
Alloc(P, 5);

你必须写

int *P = nullptr;
P = Alloc(P, 5);

否则P仍然等于nullptr。