复制构造函数在书上列举了五种应用场景,但在G++上发现,在从函数返回时,并不调用复制构造函数
/* ** Copyright (C) QPSOFT.COM All rights reserved. */ #include<string> #include<vector> #include<iostream> using namespace std; class Employee { public: Employee() : name ("NoName"), id (counter) { cout << "不带参数的构造函数!" << "/t" << ++counter << endl; } Employee (std::string nm) : name (nm), id (counter) { cout << "带参数的构造函数:" << "/t" << (++counter) << "/tEmployee (std::string nm) " << endl; } Employee (const Employee& other) : name (other.name), id (counter) { cout << "复制构造函数!" << "/t" << ++counter << endl; } Employee& operator= (const Employee& rhe) { name = rhe.name; cout << "‘=’运算符重载" << endl; return *this; } ~Employee() { cout << "析构函数" << "/t" << (counter--) << endl; } private: std::string name; int id; static int counter; }; int Employee::counter = 0; void fun1 (Employee obj) {} void fun2 (Employee& obj) {} Employee fun3() { Employee obj;//不带参数构造函数 return obj; } int main() { Employee ep;//默认构造函数 Employee ab; Employee sep ("iString"); ab = ep; //=重载 Employee tp = ep; //复制构造函数 vector<Employee> iep(5);//复制构造函数 iep.push_back (ep); //复制构造函数 iep.push_back (ab); //复制构造函数 Employee ee[] = {ep, ab, ep, ep, ab}; //会调用复制构造函数 cout << "----------下面是函数测试----------------" << endl; fun1 (ep); //复制 然后析构 cout << "-----------------------------------------"<<endl; fun2 (ep); cout << "---------------丢弃返回的fun3----------------"<<endl; fun3(); cout << "---------------保存返回的fun3------------"<<endl; ab = fun3(); cout << "---------程序返回!------------------------" << endl; return 0; }