作者sam210125 (逐風)
看板C_and_CPP
標題[問題]copy constructor和deconstructor的問題
時間Thu Apr 9 16:36:57 2015
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
VC++
問題(Question):
我的問題是下面程式碼main()裡的D=test(C)到底做了哪些事?目前
我大概知道的是因為有return by value,所以會呼叫複製建構子,
但最後到底是哪個物件呼叫解構子?我原本的理解是test()裡的物件S
會複製一份給main的物件D,並且透過複製建構子指定物件D的x,y值。
之後這個複製出來的物件S因為生命週期結束呼叫解構子。但為什麼從
輸出結果來看似乎是物件D呼叫解構子??
結果(Output):
Coordinate(double cx, double cy) call
Coordinate() call
Coordinate(const Coordinate &) call
deconstructor call!
1,1
程式碼(Code):(請善用置底文網頁, 記得排版)
class Coordinate
{
public:
Coordinate();
Coordinate(const Coordinate & S);
Coordinate(double cx, double cy);
~Coordinate();
private:
double x;
double y;
};
Coordinate test(Coordinate & S);
int main()
{
Coordinate C(4,6);
Coordinate D;
D=test(C);
system("pause");
return 0;
}
Coordinate::Coordinate()
{
cout<<"Coordinate() call"<<endl;
x=0;
y=0;
}
Coordinate::Coordinate(const Coordinate & S)
{
cout<<"Coordinate(const Coordinate &) call"<<endl;
x=1;
y=1;
}
Coordinate::Coordinate(double cx, double cy)
{
cout<<"Coordinate(double cx, double cy) call"<<endl;
x=cx;
y=cy;
}
Coordinate::~Coordinate()
{
cout<<"deconstructor call!"<<endl;
cout<<x<<","<<y<<endl;
}
Coordinate test(Coordinate & S)
{
return S;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.134.6
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1428568619.A.9BD.html
推 BlazarArc: 解構的是S啊,CD不是要等出main scope才會解構嗎 04/09 16:50
→ sam210125: 那S的x y是不是因為複製建構子變成了1,1? 04/09 16:53
→ shadow0326: 解構的是test(C)這個rvalue 04/09 18:32
→ Caesar08: 你指的S是return的S,還是parameter? 04/09 19:55
→ Caesar08: 如果是前者,是。如果是後者,不是 04/09 19:56
推 holydc: 你可以在constructor跟destructor印this的值會更清楚 04/10 04:29
→ sam210125: 有了 解構的是return的S沒錯 謝謝各位 04/10 09:21