在复制构造函数中深层复制的麻烦

时间:2013-04-12 22:18:56

标签: c++

我正在尝试通过复制构造函数创建我的类的实例的深层副本,但我无法弄清楚,如何编写它。在这一刻,当我调用复制构造函数时,程序不会崩溃然而,当我想对实例做任何事情时(即打印数组,添加一些项目等),然后程序崩溃......

有人可以告诉我,如何正确地写出来?它让我疯狂但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;
}

1 个答案:

答案 0 :(得分:4)

由于显示的代码绝不允许我们猜测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;
}