作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个关于如何调用析构函数的问题。例如,我创建了以下 foo 类并提供了复制构造函数、析构函数并重载了赋值运算符。我创建了这个 foo 对象的动态数组,并使用运算符“=”分配数组的各个元素。我很困惑,在赋值操作之后,立即调用析构函数,当我想访问新分配的对象中的数据时,我得到了非常困惑的结果。有什么建议吗?
#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/
我是一名优秀的程序员,十分优秀!