class Persion { private: std::string m_name; std::string m_addr; }; class Student : public Persion { private: std::string m_schoolName; std::string m_schoolAddr; }; bool IsValidStudent(Student s) {return true;}
Student s1; bool b_s = IsValidStudent(s1);IsValidStudent函数调用行为如下:编译器调用student拷贝构造函数拷贝实参到形参,然后形参使用完后再调用析构函数,但该类调用远不止这些,如student的父类也需要调用拷贝构造函数,而persion中有两个string成员也需要调用拷贝构造函数,还有student也有两个string成员需要调用拷贝构造函数,而且这些调用完后还需要调用析构函数。就因为一个pass-by-value操作,而需要花费这么多成本。
bool IsValidStudent(const Student &s) {return true;}这样没有调用任何的构造函数和析构函数,形参实际是实参的副本,因此需要加上const保护实参免修改。
class Persion { public: Persion(const string &name, const string& addr) : m_name(name), m_addr(addr) {} virtual ~Persion() {} //作为基类,需要定义虚析构函数 string GetName() const {return m_name;} string GetAddr() const {return m_addr;} virtual void DisPlay() {cout<<"Person\n";} private: std::string m_name; std::string m_addr; }; class Student : public Persion { public: Student(const Persion &persion, const string &sName, const string &sAddr) :Persion(persion.GetName(), persion.GetAddr()) ,m_schoolName(sName) ,m_schoolAddr(sAddr) { } string GetName() const {return m_schoolName;} virtual void DisPlay() {cout<<"Student\n";} private: std::string m_schoolName; std::string m_schoolAddr; }; void DisPlayPersion(Persion persion) { std::cout<<persion.GetName()<<endl; persion.DisPlay(); }调用
Persion p("cuancuan", "guangzhou"); Student s1(p, "shiyan", "yuexiu"); DisPlayPersion(s1);输出
void DisPlayPersion(const Persion &persion)
条款20:宁以pass-by-reference-to-const替换pass-by-value,布布扣,bubuko.com
条款20:宁以pass-by-reference-to-const替换pass-by-value
原文地址:http://blog.csdn.net/hualicuan/article/details/27564945