[英]Trouble with deep copy in copy constructor
我正在嘗試通過復制構造函數創建我的類的實例的深層副本,但我無法弄清楚,如何編寫它。在這一刻,當我調用復制構造函數時,程序不會崩潰,但是當我想對實例做任何事情(即打印數組,添加一些項目等)然后程序崩潰......
有人可以告訴我,如何寫得正確嗎? 它讓我瘋狂但O_o
struct DbChange {
const char* date;
const char* street;
const char* city;
};
class DbPerson {
public:
DbPerson(void);
const char* id;
const char* name;
const char* surname;
DbChange * change;
int position;
int size;
};
DbPerson::DbPerson() {
position = 0;
size = 1000;
change = new DbChange[1000];
}
class Register {
public:
// default constructor
Register(void);
int size;
int position;
DbPerson** db;
//copy constructor
Register(const Register& other) : db() {
db= new DbPerson*[1000];
std::copy(other.db, other.db + (1000), db);
}
};
int main(int argc, char** argv) {
Register a;
/*
* put some items to a
*/
Register b ( a );
a . Print (); // now crashes
b . Print (); // when previous line is commented, then it crashes on this line...
return 0;
}
由於顯示的代碼決不允許我們猜測Print的作用,以及它為什么會發生沖突,因此我將向您展示我對C ++的期望(而不是C和Java之間的混淆):
http://liveworkspace.org/code/4ti5TS$0
#include <vector>
#include <string>
struct DbChange {
std::string date;
std::string street;
std::string city;
};
class DbPerson {
public:
DbPerson(void);
std::string id, name, surname;
int position;
std::vector<DbChange> changes;
size_t size() const { return changes.size(); }
};
DbPerson::DbPerson() : position(), changes() { }
class Register {
public:
size_t size() const { return db.size(); }
int position; // unused?
std::vector<DbPerson> db;
Register() = default;
//copy constructor
Register(const Register& other) : db(other.db)
{
// did you forget to copy position? If so, this would have been the
// default generated copy constructor
}
void Print() const
{
// TODO
}
};
int main() {
Register a;
/*
* put some items to a
*/
Register b(a);
a.Print(); // now crashes
b.Print(); // when previous line is commented, then it crashes on this line...
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.