冗余构造
#include<iostream> #include <string> #include<time.h> using namespace std; class SuperString{ private: char *str; public: SuperString(const char *s=0):str(0){ if(s!=0){ str=new char[strlen(s)+1]; strcpy(str,s); } } SuperString(const SuperString& s):str(0){ if(s.str){ str=new char[strlen(s.str)+1]; strcpy(str,s.str); } } SuperString& operator=(const SuperString& s){ if(str!=s.str){ delete[] str; if(s.str){ str=new char[strlen(s.str)+1]; strcpy(str,s.str); } else str=0; } return *this; } ~SuperString(){delete[] str;} }; class Person{ private: SuperString name; public: Person(const char* s){ name=s; } }; class PersonTwo{ private: SuperString name; public: PersonTwo(const char* s):name(s){ } }; int _tmain(int argc, _TCHAR* argv[]) { clock_t start,finish; double totaltime; start=clock(); for(int i=0;i<10000;i++) { Person p("test"); } finish=clock(); totaltime=(double)(finish-start)/CLOCKS_PER_SEC; cout<<"\nTest 1="<<totaltime<<"秒!"<<endl; start=clock(); for(int i=0;i<10000;i++) { PersonTwo p("test"); } finish=clock(); totaltime=(double)(finish-start)/CLOCKS_PER_SEC; cout<<"\nTest 2="<<totaltime<<"秒!"<<endl; system("pause"); return 0; }
运行结果:
Test 1=0.063秒! Test 2=0.015秒!
Person p("test"); 调用两次SuperString(const char *s=0)和一次SuperString& operator=(const SuperString& s),两次 ~SuperString()
PersonTwo p("test"); 调用一次SuperString(const char *s=0),一次 ~SuperString()