gpt4 book ai didi

c++ - 删除后 C++ 中的指针

转载 作者:IT老高 更新时间:2023-10-28 23:10:47 27 4
gpt4 key购买 nike

在阅读了很多关于此的帖子后,我想澄清下一点:

A* a = new A();
A* b = a;

delete a;

A* c = a; //illegal - I know it (in c++ 11)
A* d = b; //I suppose it's legal, is it true?

所以问题是关于使用已删除指针的copy

我读过,在 c++ 11 中读取 a 的值会导致未定义的行为 - 但是读取 b 的值呢?

Trying to read the value of the pointer (note: this is different to dereferencing it) causes implementation-defined behaviour since C++14, which may include generating a runtime fault. (In C++11 it was undefined behaviour) What happens to the pointer itself after delete?

最佳答案

两者:

A* c = a;
A* d = b;

在 C++11 中未定义,在 C++14 中定义实现。这是因为 ab 都是“无效的指针值”(因为它们指向已释放的存储空间),并且“使用无效的指针值”要么是未定义的,要么是实现的定义,取决于 C++ 版本。 (“使用”包括“复制值(value)”)。

C++11 中的相关部分 ([basic.stc.dynamic.deallocation]/4) 内容如下(强调添加):

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.

带有非规范性注释说明:

On some implementations, it causes a system-generated runtime

在 C++14 中,同一部分内容如下:

If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

带有非规范性注释说明:

Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault

关于c++ - 删除后 C++ 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44182049/

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