c++ - 如何处理动态变量?
问题描述
我有几个关于动态变量和指针的问题,所以我可以更好地理解它们。
动态变量是否会在其范围到期时自动处置?如果没有,那会发生什么?
指针的值是内存地址吗?如果不是,那么它们是什么?
解决方案
It's important to understand that there two complete separate, discreet, independent "things" that you are asking about.
A pointer to an object that was created in dynamic scope (i.e. with the
new
statement).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 delete
d properly. Modern C++ has additional classes and templates that will help you do that, which you'll learn about in due time.
推荐阅读
- java - Wiremock gzip;deflate 标头被忽略?
- nginx - 我应该如何在树莓派上的 nginx 反向代理上配置 HTTPS rstudio-server 和闪亮服务器
- jquery - 如何在 Laravel 框架的 Vue 组件中使用 jquery 插件?
- react-bootstrap-table - 在 react-bootstrap-table-next 中检测 onScrollEndReached
- tensorflow - 尝试从 PIP 安装 TensorFlow 时出现错误鼻子和龙卷风未安装
- r - 如何在R中按组计算数据框列中的值?
- react-native - 如何有条件地禁用带有自定义图标的 react-native HeaderBackButton?
- javascript - 获取已定义坐标的图层和要素
- regex - 如何将正则表达式应用于列并将正则表达式匹配组保存到多个列中?
- android - 绘图的自定义视图未显示