c++中的析构函数行为
Destructor behaviour in c++
我就是不明白,当对象作为参数传递给另一个类的构造函数时,为什么要调用析构函数。这是出现问题的代码部分:
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
没有传递给函数。不能在函数内部修改
由于构造函数在函数结束后按值接受参数,因此对象超出作用域并因此被销毁。因为你不能改变构造函数的参数对象总是会被销毁所以唯一的方法就是在堆上创建一个对象的新副本(这样它就不会被销毁)然而这并不是很好的编码实践
相关文章:
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 析构函数调用
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++成员的析构函数顺序与shared_ptr
- C++ 防止在映射中放置()时调用析构函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 调用析构函数以释放动态分配的内存
- 不命名构造函数和析构函数上的类型错误