在我完成使用此对象之前调用析构函数来破坏对象

1 c++ copy-constructor shallow-copy

在我的代码中有 operator+ 重载。在这个范围内,我定义了 object ans,我想构建并返回它,但似乎析构函数ans在我可以返回它之前就进行了破坏,所以这个方法返回了一些未定义的值。

我不明白我错在哪里?它是析构函数、构建器还是在我的 operator+ 重载中?

这是我的代码:

class vector1{
    int * arr;
int size;
public:
//constructors
vector1(){}
vector1(int n){
    size=n;
    arr= new int[size];
}
//functions
int get_size(){return size;}

void init(){  //initialize all array cells to 0
    for(int i=0;i<size;i++)
        arr[i]=0;
}
int get_value_in_index(int index){
    return arr[index];
}
void set_value_in_index(int i, int num){
    arr[i]=num;
}
int & operator[](int i){
    int default_val=0;
    if (i<0 || i>size){
        cout<<"index not valid"<<endl;
        return default_val;
    }
    return arr[i];
}
vector1 operator+(vector1 & ob);

//destructor
~vector1(){
    delete [] arr;
}
};

vector1 vector1:: operator+(vector1 & ob){
vector1 ans(size);
if (ob.get_size()!=size){  //if the arrays are not the same size return array of     '0', this array size
    cout<<"vectors not the same length. can't sum them"<<endl;
    //test
    //exit(1);
    ans.init();
}
else{
    for (int i=0;i<size;i++)
        ans.set_value_in_index(i,arr[i]+ob.get_value_in_index(i));
}
return ans;
}
Run Code Online (Sandbox Code Playgroud)

感谢您的时间和帮助。

Yoc*_*mer 5

您的 operator+ 返回一个新vector1类的副本。
但是原始的(在函数开头声明的那个)在块的末尾(在右括号}之前)被销毁。

然后析构函数删除内部数组arr
所以复制的vector1对象指向一个已删除的数组。

您应该创建一个复制构造函数来复制内部数组。

vector1(const vector1& _other ){
 //copy .arr from the other one to this one
}
Run Code Online (Sandbox Code Playgroud)