gpt4 book ai didi

c++ - 删除数组

转载 作者:行者123 更新时间:2023-11-28 00:27:08 25 4
gpt4 key购买 nike

让我们假设以下代码:

    int* ptr = new int[10];
...
...
ptr += 2;
delete[] ptr;
ptr = NULL;

调用 delete 时 ptr 应该指向数组的第一个元素吗?

最佳答案

如果您对未从 new 返回的内容调用 delete,则为未定义行为

所以下面代码的结果是未定义的:

int* ptr = new int[10];
ptr += 2;
delete[] ptr;

我们也来看看标准:

C++ 2011. Section 3.7.4.2 Deallocation functions. Paragraph 3.

Otherwise, the behavior is undefined if the value supplied to operator delete(void*) in the standard library is not one of the values returned by a previous invocation of either operator new(std::size_t) or operator new(std::size_t, const std::nothrow_t&) in the standard library, and the behavior is undefined if the value supplied to operator delete[](void*) in the standard library is not one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

关于c++ - 删除数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24472841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com