简体   繁体   English

为什么 C++ 不能同时释放内存和指针

[英]why C++ can't free memory and pointer simultaneously

I have learned that in C++(download form VSCode 0.26.3) although a memory have already been freed, the pointers pointed to it won't change, which means they won't be NULL.我了解到在 C++ 中(从 VSCode 0.26.3 下载)虽然内存已经被释放,但指向它的指针不会改变,这意味着它们不会为 NULL。

Is there any method can let the pointer be NULL?有没有什么方法可以让指针为NULL?

No there is no method to do this automatically and it is important to realize that also setting the pointer to nullptr manually wont solve the general problem.不,没有自动执行此操作的方法,重要的是要意识到手动将指针设置为nullptr也无法解决一般问题。 To see why, consider this simplified example:要了解原因,请考虑以下简化示例:

int* x = new int(5);
int* y = x;
delete x;
x = nullptr;
if (x) // attempt to check if x still points to an object
    std::cout << *x;
if (y) // attempt to check if y still points to an object
    std::cout << *y;  // !! UNDEFINED BEHAVIOR !!

It is common to see pointers being set to nullptr after the call to delete .在调用delete之后,通常会看到指针被设置为nullptr However, imagine y is not in the same scope as x but some other object holds y , then there is no way that other object "knows" that y is no longer a valid pointer.但是,假设yx不在同一个范围内,但其他对象持有y ,那么其他对象“知道” y不再是有效指针是不可能的。

To avoid this and other problems smart pointers have beeen introduced and raw pointers should be avoided.为了避免这个和其他问题,已经引入了智能指针并且应该避免使用原始指针。

If you are using raw pointer then whenever you release memory assign pointer to NULL explicitly.如果您使用的是原始指针,那么每当您释放内存时,都将指针显式分配给 NULL。 There is no automatic way for raw pointers.原始指针没有自动方法。

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

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