首页 > 解决方案 > 如何处理动态变量?

问题描述

我有几个关于动态变量和指针的问题,所以我可以更好地理解它们。

动态变量是否会在其范围到期时自动处置?如果没有,那会发生什么?

指针的值是内存地址吗?如果不是,那么它们是什么?

标签: c++

解决方案


It's important to understand that there two complete separate, discreet, independent "things" that you are asking about.

  1. A pointer to an object that was created in dynamic scope (i.e. with the new statement).

  2. And the object itself, that the pointer is pointing to.

It's important for you two separate the two in your mind, and consider them as independent entities, in of themselves. Insofar as the actual pointer itself, its lifetime and scope are no different than any other object's. When it goes out of scope it gets destroyed.

But this has no effect on the object the pointer was pointing to. Only delete destroys the object. If there's some other pointer, that's still in scope, that points to the same object, you can use that pointer for the requisite delete.

Otherwise you end up with a memory leak.

And the value of the pointer is, for all practical purposes, a memory address. This is not specified in any form or fashion in the C++ standard, which defines pointers and objects in dynamic scope in terms of how their behavior is specified. However on all run-of-the-mill operating systems you'll see a memory address in the pointer.

It's also important to understand that since a pointer is an independent object, a pointer doesn't have to point to an object in dynamic scope. There are many pointers that don't. It's not a trivial task to keep track of all objects, all pointers, and to figure out which ones need to be deleted properly. Modern C++ has additional classes and templates that will help you do that, which you'll learn about in due time.


推荐阅读