深入理解C++中的复制与移动构造函数
1. 复制一个对象
在C++中,当我们创建一个新的对象并希望它与现有的对象具有相同的数据时,通常会使用复制构造函数。复制构造函数是一种特殊的构造函数,它允许我们在创建新对象时,确保新对象拥有独立的数据副本,而不是仅仅复制原始对象的引用。例如:
class Student {
public:
Student(const char* pName = "no name", int ssId = 0) : name(pName), id(ssId) {
cout << "Constructed " << name << endl;
}
// Copy constructor
Student(const Student& s) : name("Copy of " + s.name), id(s.id) {
cout << "Constructed " << name << endl;
}
~Student() {
cout << "Destructing " << name << endl;
}
protected:
string name;
int id;
};
void fn(Student copy) {
cout << "In function fn()" << endl;
}
int main() {
Student scru