简体   繁体   English

C++11 基于范围的异常错误

[英]C++11 range-based for exceptional error

I have been trying to learn The Revised C++11 and while trying a program with auto and nullptr using range-based for , I have a error: the program exits after accepting the first element of the array.我一直在尝试学习 The Revised C++11,在尝试使用基于范围的for autonullptr程序时,出现错误:程序在接受数组的第一个元素后退出。

#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 is not an array. P 不是数组。 It is defined as pointer.P它被定义为pointer.P

int *P=nullptr;

Pointers have no information about whether they point a separate single object or the first object of a sequence.指针没有关于它们是指向单独的单个对象还是指向序列的第一个对象的信息。 There are no functions begin() and end() for pointers that are implicitly used in the range based for statement.对于在基于范围的 for 语句中隐式使用的指针,没有函数begin()end()

Take into account that instead of考虑到,而不是

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

you have to write你必须写

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

otherwise P will still be equal to nullptr.否则 P 仍将等于 nullptr。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM