内存的三种分配方式
(1)Storage can be allocated before the program begins, in the static storage area. This
storage exists for the life of the program.
(2)Storage can be created on the stack whenever a particular execution point is reached (an
opening brace). That storage is released automatically at the complementary execution point
(the closing brace). These stack-allocation operations are built into the instruction set
of the processor and are very efficient. However, you have to know exactly how many
variables you need when you’re writing the program so the compiler can generate the right
code.
(3)Storage can be allocated from a pool of memory called the heap (also known as the free
store). This is called dynamic memory allocation. To allocate this memory, a function is
called at runtime; this means you can decide at any time that you want some memory and how
much you need. You are also responsible for determining when to release the memory, which
means the lifetime of that memory can be as long as you choose – it isn’t determined by
scope.
注意事项
delete can be called only for an object created by new. If you malloc( ) (or calloc( ) or
realloc( )) an object and then delete it, the behavior is undefined. Because most default
implementations of new and delete use malloc( ) and free( ), you’d probably end up
releasing the memory without calling the destructor.
If the pointer you’re deleting is zero, nothing will happen. For this reason, people often
recommend setting a pointer to zero immediately after you delete it, to prevent deleting it
twice. Deleting an object more than once is definitely a bad thing to do, and will cause
problems.
new的流程
When you create a new-expression, two things occur. First, storage is allocated using the
operator new( ), then the constructor is called. In a delete-expression, the destructor is
called, then storage is deallocated using the operator delete( ).
Overloading new & delete
(1)global overloading
所有的new,delete都被overload,这样做不是很好,因为很难定义所有类的new,delete
(2)overloading for a class
chap13 Dynamic Object Creation
最新推荐文章于 2023-08-11 13:41:47 发布