为什么没有调用析构函数

Why is the destructor not called?

本文关键字:析构函数 调用 为什么      更新时间:2023-10-16

这是合乎逻辑的,在堆栈上创建对象…返回对象的副本,删除原始对象

Box operator +(const Box& box) const 
{
    Box b = Box(this->num + box.num);
    return b;                        
}  // destructor called!

为什么在这种情况下过程不同??

Box operator +(const Box& box) const 
{
    return Box(this->num + box.num);
}   // destructor not called!

为什么在第二个操作符重载方法中没有调用析构函数?

您看到的是编译器没有通过执行返回值优化来创建临时对象。

没有调用析构函数,因为编译器可以在这里执行"返回值优化"。