我必须加深对调用构造函数的情况的理解。在此期间,我偶然发现了Microsoft 的这个示例:
//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
但是我不能完全跟随。我认为这就是发生的事情:
- 主要
constructor
要求RVO rvo;
- 在 MyMethod
constructor
中调用RVO rvo;
- 因为
return (rvo);
被copyconstructor
称为 - 在 MyMethod
destructor
中为本地 RVO 调用 destructor
本地 rvo 调用In Main
这让我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;
};