More Effectvie C++笔记(四)--不要重载“&&”“||”或“,”、理解各种不同含义的new和delete

ITEM7:不要重载“&&”、“||”或“,”

    短路求值法

对于&&与||,在C/C++中使用布尔表达式短路求值法(short-circuit evaluation),表达式一旦确定真假值,即使还有部分表达式没有被测试,布尔表达式也停止运算。

    char *p;

    if((p !=0) && (strlen(p) > 10))…

    代码中不必担心p为空时strlen无法正确运行,因为p不等于0测试失败,不会再调用strlen。

    重载&&、||

如果operator&&和operator||,if (expression1 && expression2) ...对于编译器来说,等同于下面代码之一:

if(expression1.operator&&(expression2))

//whenoperator&& is a member function                

if(operator&&(expression1, expression2))

//when operator&& is a global function

    产生问题

①    两个参数都需要计算,没有采用短路计算法。

②    没有办法知道表达式1与表达式2哪一个先计算。完全可能与具有从左参数到右参数计算顺序的短路计算法相反。

逗号操作符

for (int i =0, j = strlen(s)-1; i < j; ++i, --j)            // 逗号操作符

包含逗号的表达式首先计算逗号左边的表达式,然后计算逗号右边的表达式;整个表达式的结果是逗号右边表达式的值。

由于不能控制函数参数的计算顺序,故不可重载。

不可重载的操作符

.

.*

::

?:

new

delete

sizeof

typeid

static_cast

dynamic_cast

const_cast

reinterpret_cast

 

    可重载的操作符

operator new

operator delete

operator

new[]

operator delete[]

+

-

*

/

%

^

&

|

~

!

=

+=

-=

*=

/=

%=

^=

&=

|=

<< 

>> 

>>=

<<=

==

!=

<=

>=

&&

||

++

--

,

->*

->

()

[]

 

 

ITEM8:理解各种不同含义的new和delete

    new操作符

string*ps = new string("Memory Management");

    new操作符的2个功能:①分配足够的内存容纳所需类型的对象;②调用构造函数初始化内存中的对象。

    operator new

    功能是分配内存,声明方式:

              void*operator new(size_t size);

    例:

void*memory =  operator new(sizeof(string));// 得到未经处理的内存为String对象

callstring::string("Memory Management") on *memory; //初始化内存中的对象

string*ps = static_cast<string*>(memory);         //是ps指针指向新的对象

    placement new

    一些已经被分配但尚未处理的(raw)内存,在这些内存中构造一个对象,可以使用特殊的operatornew,被称为placementnew。使用它时,必须使用语句#include<new>。

    例:

              classWidget {

public:

                           Widget(int widgetSize);

};

Widget *constructWidgetInBuffer(void *buffer, int widgetSize)

{

             returnnew (buffer) Widget(widgetSize);

}

    三种new方式的区别

①    new:在堆上建立一个对象应该使用new。

②    operator new:仅想分配内存。

③    placement new:想在一块已经获得指针的内存里建立一个对象。

operator delete

operatordelete用来释放内存,声明:

void operatordelete(void *memoryToBeDeallocated);

数组

使用operator new[],operator delete[]。

(待续……)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值