gpt4 book ai didi

c++ - 关于对象数组中的析构函数

转载 作者:行者123 更新时间:2023-11-27 23:10:01 27 4
gpt4 key购买 nike

我有一个关于如何调用析构函数的问题。例如,我创建了以下 foo 类并提供了复制构造函数、析构函数并重载了赋值运算符。我创建了这个 foo 对象的动态数组,并使用运算符“=”分配数组的各个元素。我很困惑,在赋值操作之后,立即调用析构函数,当我想访问新分配的对象中的数据时,我得到了非常困惑的结果。有什么建议吗?

enter image description here

#include <iostream>

using namespace std;
bool debug = true;

class foo{
private:
int n;


void init(int _n);
public:

int* arr; // just to make it accessible so that we can tract the contents;

foo(int _n);
foo(int* _a, int len);
foo(const foo & rhs);
foo & operator=(const foo & rhs);
~foo();
};


void foo::init(int _n = 0){
n = _n;
arr = new int[n];
for(int i = 0; i != n; i++) arr[i] = 0;
}

foo::foo(int _n = 0){
init(_n);
}

foo::foo(int*_a, int len){
init(len);
for(int i = 0; i< len; i++) arr[i] = _a[i];
}

foo::foo(const foo &rhs){
operator = (rhs);
}

foo& foo::operator= (const foo &rhs){
if(debug) cout<<"\nassignment operator overloaded";
if (this != &rhs){
if(n != 0) {
n = rhs.n;
delete [] arr;
arr = new int[n];
for(int i = 0; i < n; i++) arr[i] = rhs.arr[i];
}
}
return *this;
}

foo::~foo(){
if (debug)cout << "\ndestructor called\n";
delete []arr;
}

int main(){

{ // a explicit block to see when the destructor is called;
foo* f = new foo[4];
int n = 4;
int a[] = {0,1,2,3};
for(int i = 0; i < n;i++) {
cout<<i;
f[i] = foo(a, i);
cout<<f[i].arr[i]<<"\n"; // result is some seemingly random number;
}
}

system("PAUSE");
}*

最佳答案

当你这样做时:

f[i] = foo(a, i);

临时 foo 对象在赋值运算符的 RHS 上创建。然后用于分配给运算符(operator) LHS 上的 foo。然后,它被销毁,因此它的析构函数被调用。

赋值后出现垃圾值的原因可能是数组中所有foos中的n都是0。您的赋值运算符已损坏。您可能想看看 copy and swap idiom .

关于c++ - 关于对象数组中的析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20907538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com