C++ new and delete

[size=large][b][align=center]C++ new and delete[/align][/b][/size]

摘自:C++_Primer_Plus_4th
Classes Whose Constructors Use new
Classes that use the new operator to allocate memory pointed to by a class member require several precautions in the design. (Yes, we summarized these precautions recently, but the rules are very important to remember, particularly because the compiler does not know them and, thus, won't catch your mistakes.)

1.Any class member pointing to memory allocated by new should have the delete operator applied to it in the class destructor. This frees the allocated memory.

2.If a destructor frees memory by applying delete to a pointer that is a class member, then every constructor for that class should initialize that pointer either by using new or by setting the pointer to the null pointer.

3.Constructors should settle on using either new [] or new, but not a mixture of both. The destructor should use delete [] if the constructors use new [], and it should use delete if the constructors use new.

4.You should define a copy constructor that allocates new memory rather than copying a pointer to existing memory. This enables a program to initialize one class object to another. The constructor normally should have the following form of prototype:

className(const className &)

5.You should define a class member function overloading the assignment operator and having the following form of function definition (here c_pointer is a member of the c_name class and has the type pointer-to-type_name):

c_name & c_name::operator=(const c_name & cn)
{
if (this == & cn_)
return *this; // done if self-assignment
delete c_pointer;
c_pointer = new type_name[size];
// then copy data pointed to by cn.c_pointer to
// location pointed to by c_pointer
...
return *this;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值