class Person
{
...
}
class Student : public Person
{
...
}
bool validateStudnt(Student s);
Student plato;
bool platoIsOk = validateStudent(plato);
对此参数而言,参数的传递成本是“一次Student copy构造函数调用,加上一次Student析构函数调用”。
Student对象内还有两个string对象,所以每次构造一个Student对象也就构造了两个string对象,此外student对象还继承Person对象,所以student对象每次构造也会构造一份Person对象。一个Person对象也有两个string对象,因此一个Person对象构造动作又须承担两个string构造动作。
所以最终结果是以值传递一个student对象会导致一次student copy构造函数,一次Person copy函数,四次stirng copy构造函数,六次析构函数。
bool validateStudent( const Student & s);
这种传递方式的效率高得多;没有任何构造函数或析构函数被调用,因此没有任何新对象被创建。const函数内绝不会对引入的student做任何改变。
而且以引用传递参数还可以避免对象切割问题。
class Window
{
public :
,,,
std::string name() const;
virtual void display() cosnt ;
};
class WindowWithScrollBars: public Window
{
public:
....
virtual void display() const;
};
void printNameAndDisplay( Window w) //不正确!参数Window可能被切割
{
std::cout<<w .name();
w.dispaly();
}
WindowWithScrollBars wwsb;
printNameAndDisplay( wwsb); //危险!对象都会被切割成Window对象,无论传递什么类型,参数w都会被切割。
void printNameAndDisplay( const Window & w)
{
std:: cout<< w. name();
w.display();
}
1.尽量以传引用const替换以值传递。前者通常比较高效,并可避免切割问题。
2.以上规则不适用内置类型(int类型)以及STL的迭代器和函数对象。对他们而言,以值传递往往比较合适。