C + + Programming Ideas reading notes (1)-Heaps and stacks

Source: Internet
Author: User

Creating and destroying objects


There are two types of storage areas for objects

Storing objects in stacks or static storage can be determined by the time the program is written.

static storage, which mainly stores global variables, constants, and static data, which are already allocated when the program is compiled.

Stacks, which mainly store local variables. These variables are generated in the stack when the function runs, and are automatically released when the function ends.

The second is to create objects dynamically in the heap.

Because there are ways to know that the runtime is not sure how many objects are needed, you can only do it when it is needed, and the new objects are generated on the heap, and use Delete to release them when they are finished.


The difference between stacks and heaps


1, the required operating time

Because the heap is dynamically managed when it is stored, it takes more time to allocate space on the heap than on the stack (the creation space on the stack is often just a microprocessor instruction to move the stack pointer downward, and the other is to move back to the instruction).

2, the life cycle of the object

The lifecycle of an object on the stack, determined by the compiler's lifetime and can be automatically destroyed. The lifecycle on the heap, the compiler is out of control, and the programmer needs to decide when to destroy and use Delete to perform the destruction task.

Of course, Java and other programs have provided the function of garbage collector, for programmers save a lot of unnecessary trouble.



~end~

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.