c++ - What's the difference between data stored in global variables and data stored in the heap? -


int globalint = 1;   int main(){     int* heapint = new int(1); } 

what difference between globalint , heapint? know heapint points in heap, , know globalint goes global data storage, difference? why use 1 on other?

thank in advance help.

a global variable has static storage duration. means object exists when program starts when ends. exists entire duration of program.

the int created new-expression has dynamic storage duration. it's lifetime begins new-expression , ends when delete heapint;.

you can think of these 2 storage durations being opposite ends of spectrum. global variable gives least control on lifetime because exists. dynamically allocated object gives control, because can create , destroy @ point in code.

it's worth noting global variable has name. makes object accessible parts of code in name in scope. in contrast, access dynamically allocated object, need have been given pointer it.

global variables considered bad practice because introduce global state program. is, might have function modifies or uses global variable without making clear in interface. means function may have secret side effects, leading unpredictable , unmaintainable code hard test.

on other hand, dynamically allocated objects necessary should used carefully. important ensure lifetime of object managed appropriately. 1 approach use raii, objects dynamically allocated in constructors , correspondingly destroyed in destructors. additional modern approach avoid doing memory management entirely , use smart pointers instead.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -