我才知道,爲什麼要使用拷貝構造函數之一是避免後續崩潰的程序 -複製構造函數的動機 - 爲什麼我的程序不會崩潰?
#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;
}
取決於什麼在你的構造函數和析構函數...還有,UB意味着什麼* *可能發生,甚至根本工作。 – Xeo
我猜在析構函數中有'delete this-> m_name()',崩潰是由於「double free detected」造成的。 – Greg
@Greg我認爲你釘了它。在構造函數代碼中分配。優秀的心理調試。 –