为什么我的析构函数被调用两次? [英] Why is my destructor called twice?

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

问题描述

假设我使用以下方法让班级学生:

 学生:: method(Student x)
{
//没有重要的
返回x;
}

复制构造函数被调用两次,一次是当对象x作为a发送时



为什么当我调用此方法时以及何时类的学生的析构函数被调用两次?
调用是这样的:a = b.method(c),其中a,b和c是Student对象。

解决方案

在您的示例中, a = b.method(c); 可能会发生三份副本,但要保留副本。第一种是将 c 对象复制到函数参数 x 中。第二个是从函数返回 x 对象时。第三是将返回值复制到 a 对象中。前两个涉及复制构造函数,最后两个涉及复制赋值运算符,除非您将其更改为 Student a = b.method(c); ,在这种情况下,它们全部使用副本构造函数。



a b ,和 c 都将在范围结束时销毁。 x 对象将在 method 函数的末尾销毁。函数的返回值将在包含该函数的完整表达式的末尾被破坏-即,一旦 a = b.method(c); 完成。 / p>

但是,并非所有这些副本都必须发生-在某些情况下允许编译器 elide 或省略类的副本/移动构造。将出现到function参数的第一个副本。在尝试复制该功能之前,该功能以外的第二个副本将被视为先行动作。此副本或移动可能会被删除。如果使用副本分配,则会出现最终副本,从临时返回值到 a ,但是如果使用副本构造函数,最终副本可能会被忽略(如学生a = b。方法(c); )。


Suppose I hace a class Student with the method:

Student Student::method(Student x)
{
    //nothing important
    return x;
}

The copy constructor is called twice, once when the object x is send as a parameter and second when x is returned from the function.

Why and when is the destructor for class Student called twice when I call this method? The call is like this: a = b.method(c), where a, b and c are Student objects.

解决方案

For your example, a = b.method(c);, there are three copies that may take place, save for copy elision. The first is when the c object is copied into the function parameter x. The second is when the x object is returned from the function. The third is when the return value is copied into the a object. The first two involve the copy constructor and the last involves the copy assignment operator, unless you change it to Student a = b.method(c);, in which case they all use the copy constructor.

a, b, and c will all be destroyed at the end of their scope. The object x will be destroyed at the end of the method function. The return value of the function will be destroyed at the end of the full expression that contains it - that is, once a = b.method(c); has finished.

However, not all of these copies must occur - the compiler is allowed to elide or omit the copy/move construction of a class under certain situations. The first copy into the function parameter will occur. The second copy out of the function will be treated as a move first, before attempting to copy it. This copy or move may be elided. The final copy, from temporary return value to a, will occur if you're using copy assignment, but may be elided if you use the copy constructor (as in Student a = b.method(c);).

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

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