C ++复制构造函数运行时错误

时间:2014-03-06 23:50:44

标签: c++ class runtime-error move copy-constructor

我在c ++中创建了一个应用程序,用户在其中写入一些随机数(放在一个数组中)并显示给他,然后使用复制构造函数再次显示他的输入年龄。但这里的问题是复制功能执行,但它不显示任何信息。 这是我的代码:

#include <iostream>
#include <string>
using namespace std;

class Identity{
protected:
    int* arry_int;
    int ages;
    Identity(){} //private default constructor
public:
    Identity(int repeated_number){ //overloaded constructor
        ages = repeated_number  ;
        arry_int = new int [ages];
    }
    void getAge(){ //getting age form the user
        for (int i = 0; i < ages; i++){
            cout << "Enter age[" << i << "]: ";
            cin >> arry_int[i];
        }
    }
    void printAge(){
        cout << "Friend's ages" << endl;
        cout << "-----------------" << endl;
        for (int i = 0; i < ages; i++){
            cout << arry_int[i] << endl;
        }
    }
    //move copy constructor
    Identity(Identity&& cpy){
        cout << "Declaring move constructor" << endl;
        arry_int = cpy.arry_int;
        cpy.arry_int = NULL;
    } 
    //move assignment operator
    Identity& operator=(Identity&& cpy){
        cout << "Declaring move assignment operator" << endl; 
        if (this != &cpy){
        delete arry_int;
        arry_int = cpy.arry_int;
        cpy.arry_int = NULL;
        }
        return *this;
    }
    ~Identity(){
        delete arry_int;
    }
};

int main(){
    string nemesis;
    Identity iden(5);
    iden.getAge();
    iden.printAge();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    cout << "Enter your nemesis name: " << endl;
    getline(cin,nemesis);
    //nemesis stealing your identit
    Identity stolen(move(iden));
    cout << "Now " << nemesis << " stole your friend's age and used it against you" << endl;
    stolen.printAge();
    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:3)

您忘记在移动构造函数中复制数据成员年龄。

必须有

//move copy constructor
Identity(Identity&& cpy){
    cout << "Declaring move constructor" << endl;
    arry_int = cpy.arry_int;
    cpy.arry_int = NULL;
    ages = cpy.ages;
} 

同样适用于移动赋值运算符

//move assignment operator
Identity& operator=(Identity&& cpy){
    cout << "Declaring move assignment operator" << endl; 
    if (this != &cpy){
    delete arry_int;
    arry_int = cpy.arry_int;
    cpy.arry_int = NULL;
    ages = cpy.ages;
    }
    return *this;
}

析构函数也应定义为

~Identity(){
        delete []arry_int;
}

不知道为什么你将默认构造函数声明为protected。