`
kuwoleft
  • 浏览: 1078752 次
文章分类
社区版块
存档分类
最新评论

宁以pass-by-reference-to-const替换pass-by-value——effective c++学习笔记

 
阅读更多

<!--[endif]-->宁以pass-by-reference-to-const替换pass-by-valuePrefer pass-by-conference-to-const to pass-by-value.

pass-by-conference-to-const

class Point

{

public:

Point( ) : xval(2), yval(2){printf("%d,%d/n", xval, yval);}

void SetXval(int i){xval = i;}

private:

int xval, yval;

};

void const_test(const Point *p)

{

p->SetXval(9);

}

Point *p = new Point();

const_test(p);

这样会编译出错:

“错误:将 const Point 作为 void Point::SetXval(int) this 实参时丢弃了类型限定”

也就是说,“const Point *p”,p的成员不可以发生更改。

类似,Point 的成员函数:

void SetXval(int i)const{xval = i;}

则也会编译出错,因为在SetXval函数中,thisconst的。const会修饰conference

pass-by-value

void const_test(Point p)

{

}

Point p;

const_test(p);

这样操作,从p到函数实参,会涉及一次copy构造函数调用。

pass-by-conference-to-const优势:

<!--[if !supportLists]-->1、 <!--[endif]-->没有任何构造函数和析构函数被调用。

<!--[if !supportLists]-->2、 <!--[endif]-->可以避免slicing(对象切割问题):当一个derived classby-value的方式传递并被视为一个base class对象,base class的构造copy构造函数可以被调用,这样新的对象中,derived class部分会被丢弃掉,而获得一个base class对象。这样调用virtual函数是,会调用base class的,而不是预期中的derived的。

<!--[if !supportLists]-->3、 <!--[endif]-->对于内置类型对象,STL的迭代器,函数对象,pass by-value往往比pass-by-reference-to-const 效率高些。除此之外,其他尽量以pass-by-reference-to-const代替pass-by-value

注意:

<!--[if !supportLists]-->1、 <!--[endif]-->尽量以pass-by-reference-to-const代替pass-by-value。前者通常比较高效,并可避免切割(slicing)问题。

<!--[if !supportLists]-->2、 <!--[endif]-->以上规则并不适用内置类型对象,STL的迭代器,函数对象。对他们而言,pass-by-value往往比较适当。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics