为什么析构函数不从函数中返回的对象调用? [英] Why is the destructor not called for the returned object from the function?

查看:323
本文介绍了为什么析构函数不从函数中返回的对象调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为当一个函数返回一个堆栈上的对象到调用函数时,调用函数会获取原始对象的副本,但是一旦堆栈展开,就会调用原始对象的析构函数。但是在下面的程序中,析构函数只被调用一次。我期望它被调用两次。

I was thinking that when a function returns an object on the stack to the calling function, the calling function gets a copy of the original object but the original object's destructor is called as soon as the stack unwinds. But in the following program, the destructor is getting called only once. I expected it to be called twice.

#include <iostream>

class MyClass
{
public:
  ~MyClass() { std::cout << "destructor of MyClass" << std::endl; }
};

MyClass getMyClass()
{
  MyClass obj = MyClass();
  return obj;   // dtor call for obj here?
}

int main()
{
  MyClass myobj = getMyClass();
  return 0;  // Another dtor call for myobj.
}

但是MyClass的析构函数只被打印一次。

But "destructor of MyClass" is getting printed only once. Is my assumption wrong or is there something else going on here?

推荐答案

这是一个特殊情况,允许编译器优化复制:这称为命名的返回值优化(NRVO)。基本上,编译器为调用点上的返回对象分配内存,并让函数直接填充该内存,而不是在被调用的站点处创建对象,并将其复制回来。现代编译器在可能的情况下(在某些情况下,这是不容易的,因为在函数中有多个返回路径返回不同实例)。

This is a special case where the compiler is allowed to optimize out the copy: this is called named return value optimization (NRVO). Basically, the compiler allocates memory for the return object on the call site and lets the function fill in that memory directly instead of creating the object at the called site and copying it back. Modern compilers do this routinely whenever possible (there are some situations where this isn't easy since there are several return paths in the function that return different instances).

这篇关于为什么析构函数不从函数中返回的对象调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆