我了解到使用复制构造函数的动机之一是避免程序中的后续崩溃 -
#include <iostream>
using namespace std;
class Employee {
public:
Employee(int ID,char const * name){...};
~Employee(){...};
// Methods
void Print();
private:
// members
int m_ID;
char* m_name;
};
void MyFunc(Employee emp) {
cout << "in MyFunc \n ";
}
int main() {
Employee One(1,"Garen Torosian");
// calling copy constructor
MyFunc(One);
cout << "In the end of main \n";
// Here the program crashes!
return 0;
}
如您所见,该程序应该在之前崩溃return 0;
,但是当我运行该程序时,它运行正常并且正常终止,为什么?
编辑:在这种情况下,程序确实崩溃了-
// Employee.h
#include <iostream>
using namespace std;
class Employee {
public:
Employee(int ID,
const char* name);
~Employee();
// Methods
void Print();
private:
// members
int m_ID;
char* m_name;
};
// Employee.cpp
#include "Employee.h“
Employee::Employee(int iID, const char *name){ // Ctor
cout << "Constructor called" << endl;
m_ID = iID;
m_name = new char [strlen(name) +1];
strcpy(m_name, name);
Print();
}
void Employee::Print() { // Print
cout << "ID: " << m_ID << ",Name:” << m_name
<< " ,Address(pointer):0x" << hex << (int) m_name<< endl;
}
Employee::~Employee() { // Dtor
cout << "Destructor called"<<endl;
Print();
delete [] m_name;
m_name=NULL;
}
void MyFunc(Employee emp) {
cout << "in MyFunc \n ";
}
int main()
{
Employee One(1,"Eli Rachamim");
// calling copy constructor
MyFunc(One);
cout<< "In the end of main \n“;
// Here the program crashes!
return 0;
}