include <iostream>
#include <stdio.h>
using namespace std;
class Cexample
{
private:
int a;
public:
Cexample(int b)
{
a = b;
printf("constructor is callec\n");
}
Cexample(const Cexample & c)
{
a = c.a;
printf("copy constructor is called\n");
}
~Cexample()
{
cout << "destructor is called\n";
}
void show()
{
cout << a << endl;
}
};
Cexample g_fun(Cexample c)
{
cout << "g_func"<<endl;
}
int main()
{
Cexample A(100);
Cexample B=A;
B.show();
g_fun(A);
return 0;
}
運行結果:
constructor is callec
copy constructor is called
100
copy constructor is called
g_func
destructor is called
destructor is called
destructor is called
destructor is called
原文只有三個destructor is called,我運行的為啥有4個,疑問?
/*****************************************************************/
#include <iostream>
#include <stdio.h>
using namespace std;
class Cexample
{
private:
int a;
public:
Cexample(int b)
{
a = b;
printf("constructor is callec\n");
}
Cexample(const Cexample & c)
{
a = c.a;
printf("copy constructor is called\n");
}
~Cexample()
{
cout << "destructor is called\n";
}
void show()
{
cout << a << endl;
}
};
Cexample g_fun()
{
Cexample temp(0);
return temp;
}
int main()
{
g_fun();
return 0;
}
運行結果:
constructor is callec
destructor is called
原文運行結果:
constructor is callec
copy constructor is called
destructor is called
destructor is called
怎么和原文:
https://www.cnblogs.com/alantu2018/p/8459250.html
運行結果很不同呢,請各位幫忙看一下!謝謝!
uj5u.com熱心網友回復:
會不會是和編譯器的自動優化有關? 你用的是什么編譯器,用的是debug,還是release?uj5u.com熱心網友回復:
理論上列印問題1
Cexample A(100); //1:constructor is callec
Cexample B=A; //2:copy constructor is called
B.show(); //3:100
g_fun(A);//4: copy constructor is called(引數拷貝),5: g_func(函式內列印),6: destructor is called(引數析構),7: destructor is called(回傳值析構)
return 0; //8: destructor is called(A析構),9: destructor is called(B析構)
和原文運行結果不同,是因為g_fun()忘了return回傳值,回傳值不確定,不同編譯器可能對這個不確定回傳值的處理不同
問題2
Cexample temp(0); //1: constructor is callec
return temp; //2: copy constructor is called(回傳值拷貝),3: destructor is called(區域變數temp析構),4: destructor is called(回傳值析構)
和原文運行結果不同,估計是編譯器優化了,因為main沒有使用回傳值
uj5u.com熱心網友回復:
你的代碼能通過編譯嗎Cexample g_fun(Cexample c)
{
cout << "g_func"<<endl;
}
這段代碼沒有回傳值啊
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/169717.html
標籤:C++ 語言
下一篇:多執行緒如何對陣列下標同步
