何时将临时的析构函数称为 [英] When is the destructor of the temporary called

查看:96
本文介绍了何时将临时的析构函数称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道C ++ 03和C ++ 11何时调用temporay的析构函数

I wanted to know when the destructor of a temporay is called for both C++03 and C++11

假设我遇到以下情况

foo method()
{
   foo f;
   ......
   ......
   return foo;
}

void doSomething()
{
   foo f = method();
   ....
}

假设我使用的标志 -fno-elide-constructors ,因为我想从理论上了解何时调用临时结构的析构函数。
因此,根据 C ++ 03 中的上述代码,当 method()完成时, foo 是使用其副本构造函数创建的。之后,在语句 foo f = method()处再次调用 foo 的副本构造函数。 在这种情况下,对于C ++ 03,此临时变量的析构函数(由方法传递)何时称为? doSomething()
的范围现在,我想将相同的情况应用于涉及移动语义的C ++ 11。对于C ++ 11,当方法返回 foo 的副本时,则创建 foo f = method()被称为foo的move构造函数。 因此,对于C ++ 11,何时从 method()返回的临时对象的析构函数称为?

Suppose I am using the flag -fno-elide-constructors since I would like to get a theoretical understanding of when the destructor of a temporary is called. So from the above code in C++03 when the method() is finished a copy of foo is made using its copy constructor. After that at the statement foo f = method() the copy constructor of foo is called again. In this case for C++03 when is the destructor of this tempoary (which was passed by method) called ? Is it called at the end of scope of doSomething() Now I would like to apply the same case to C++11 which involve the move semantics. In case of C++11 when method returns a copy of foo is made.Then when foo f = method() is called the move constructor of foo is called. So in case of C++11 when is the destructor of the temporary object returned from method() called ?

推荐答案


我想知道何时同时为
C和C + +调用temporay的析构函数+11

I wanted to know when the destructor of a temporay is called for both C++03 and C++11

在表达式的末尾调用R值的析构函数(临时)。

The destructor of an R-Value (temporary) is called at the end of the expression.

提供您的代码:

foo method()
{
   foo f;
   ......
   ......
   return foo;
}

void doSomething()
{
   foo f = method();
   ....
}

method()创建一个对象。当该对象超出范围时(在方法末尾),将调用析构函数(在没有优化的情况下)。

method() creates an object. When that object goes out of scope (at the end of method), the destructor is called (in the event of no optimisations).

调用 foo f = ...导致foo的副本构造函数被调用。之后,表达式结束,导致返回的对象(临时)被破坏。在doSomething结束时,对象 f的析构函数会超出范围。

The call "foo f="... causes the copy constructor for foo to be called. After that the expression ends, causing the returned object (temporary) to be destructed. The object "f"'s destructor is called when it goes out of scope at the end of doSomething.

这篇关于何时将临时的析构函数称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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