c++中的析构函数行为

Destructor behaviour in c++

本文关键字:析构函数 c++      更新时间:2023-10-16

我就是不明白,当对象作为参数传递给另一个类的构造函数时,为什么要调用析构函数。这是出现问题的代码部分:

Ocean* sea=new Ocean(4,3,7);
sea->print();
RunLengthEncoding* s2= new RunLengthEncoding(*sea);
sea->print();
构造函数的代码:
RunLengthEncoding::RunLengthEncoding(Ocean sea)
{
oceanEncoding = new MyLinkedListD();
height = sea.height();
width=sea.width();
starveT=sea.starveTime();
int length=1;
int cellType=sea.cellContents(0,0);
int hunger=sea.sharkFeeding(0,0);
for(int row=0;row<height;row++){
    for(int col=0;col<width;col++){
        if(row==0&&col==0){
            cellType=sea.cellContents(col,row);
            hunger=sea.sharkFeeding(col,row);
        }
        else{
            if(sea.cellContents(col,row)==cellType && ((cellType==Ocean::SHARK && hunger==sea.sharkFeeding(col,row))|| cellType!=Ocean::SHARK)){
                    length++;
            }
            else{
                oceanEncoding->add(cellType,length,hunger);
                cellType=sea.cellContents(col,row);
                length=1;
                hunger=sea.sharkFeeding(col,row);
            }
        }
    }
}
oceanEncoding->add(cellType,length,hunger);
internalPointer=oceanEncoding->getHead();
check();

}

构造函数按值接受实参。创建、使用一个副本,然后在构造函数返回时销毁该副本。

通过引用接受实参(最好是const引用)

RunLengthEncoding(*sea);

接受一个值。不是指向某个值的指针,也不是对某个值的引用。编译器插入代码来创建一个值,并将其传递给函数。在函数内部,如果你修改了值,它不会改变你想象中传入的值。函数调用后,该值被销毁。

*sea没有传递给函数。不能在函数内部修改

由于构造函数在函数结束后按值接受参数,因此对象超出作用域并因此被销毁。因为你不能改变构造函数的参数对象总是会被销毁所以唯一的方法就是在堆上创建一个对象的新副本(这样它就不会被销毁)然而这并不是很好的编码实践