chap13 Dynamic Object Creation

 
内存的三种分配方式

(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值