gpt4 book ai didi

c++ - 析构函数和构造函数调用,例子对吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:54:08 25 4
gpt4 key购买 nike

我必须完善我对调用构造函数的情况的理解。在此期间,我偶然发现了 this example来自微软:

//RVO class is defined above in figure 4
#include <stdio.h>
RVO MyMethod (int i)
{
RVO rvo;
rvo.mem_var = i;
throw "I am throwing an exception!";
return (rvo);
}
int main()
{
RVO rvo;
try
{
rvo=MyMethod(5);
}
catch (char* str)
{
printf ("I caught the exception\n");
}
}

RVO 类在调用时仅具有构造函数、copyconsdtuctor 和析构函数打印。微软声明,如果 thorw 被注释掉并且没有 NRVO,输出将是:

I am in constructor
I am in constructor
I am in copy constructor
I am in destructor
I am in destructor
I am in destructor

但是我不太明白。我认为这就是发生的事情:

  1. 在主构造函数中调用RVO rvo;
  2. 在 MyMethod 中 constructorRVO rvo;
  3. 调用
  4. 对于return (rvo);,调用了copyconstructor
  5. 在 MyMethod 中为本地 RVO 调用 析构函数
  6. 在 Main destructor 中为本地 rvo 调用

这使我的 destructor 调用比微软宣称的少了一次。我错过了什么?

RVO 类的完整性:

class RVO
{
public:

RVO(){printf("I am in constructor\n");}
RVO (const RVO& c_RVO) {printf ("I am in copy constructor\n");}
~RVO(){printf ("I am in destructor\n");}
int mem_var;
};

最佳答案

如果你仔细看语句 rvo=MyMethod(5);

rvo由MyMethod的返回对象赋值,返回对象应该在main函数的作用域内构造。该对象未命名,是一个临时对象。这样一个对象的构造函数显示在输出中,乍一看并不明显。

关于c++ - 析构函数和构造函数调用,例子对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12489781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com