C ++:全局变量作为指针 [英] C++: Global variable as pointer

查看:149
本文介绍了C ++:全局变量作为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,对全局变量有一个疑问.我在许多示例中看​​到,全局变量是带有堆地址的指针.因此,指针位于全局/静态变量的内存中,而地址后面的数据位于堆中,对吗?
代替此,您可以声明存储数据的全局(无指针)变量.因此,数据存储在内存中以用于全局/静态变量,而不是堆中.
与第一个使用指针和堆的解决方案相比,此解决方案有什么缺点吗?

I am new to c++ and have one question to global variables. I see in many examples that global variables are pointers with addresses of the heap. So the pointers are in the memory for global/static variables and the data behind the addresses is on the heap, right?
Instead of this you can declare global (no-pointer) variables that are stored the data. So the data is stored in the memory for global/static variables and not on the heap.
Has this solution any disadvantages over the first solution with the pointers and the heap?


第一个解决方案:


First solution:

//global 
Sport *sport;
//somewhere
sport = new Sport;

第二种解决方法:

//global
Sport sport;

推荐答案

将数据存储在全局/静态变量中的一个缺点是,大小在编译时是固定的,与堆存储不同,不能更改大小可以在运行时确定,并在运行过程中反复增大或缩小.生存期也固定为全局/静态变量从头到尾完成程序的完整运行,与堆存储相反,在整个运行期间都可以获取和释放(甚至重复)堆存储.另一方面,全局和静态存储管理全部由编译器为您处理,因为堆存储必须由您的代码显式管理.因此,总而言之,全局/静态存储更容易,但不如堆存储灵活.

A disadvantage of storing your data in a global/static variable is that the size is fixed at compile time and can't be changed as opposed to heap storage where the size can be determined at runtime and grow or shrink repeatedly over the run. The lifetime is also fixed as the complete run of the program from start to finish for global/static variables as opposed to heap storage where it can be acquired and released (even repeatedly) all through the runtime of the program. On the other hand, global and static storage management is all handled for you by the compiler where as heap storage has to be explicitly managed by your code. So in summary, global/static storage is easier but not as flexible as heap storage.

这篇关于C ++:全局变量作为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆