[問題] copy constructor和deconstructor的問題

作者: sam210125 (逐風)   2015-04-09 16:36:57
開發平台(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;
}
作者: BlazarArc (Midnight Sun)   2015-04-09 16:50:00
解構的是S啊,CD不是要等出main scope才會解構嗎
作者: sam210125 (逐風)   2015-04-09 16:53:00
那S的x y是不是因為複製建構子變成了1,1?
作者: shadow0326 (非議)   2015-04-09 18:32:00
解構的是test(C)這個rvalue
作者: Caesar08 (Caesar)   2015-04-09 19:55:00
你指的S是return的S,還是parameter?如果是前者,是。如果是後者,不是
作者: holydc (のヮの)   2015-04-10 04:29:00
你可以在constructor跟destructor印this的值會更清楚
作者: sam210125 (逐風)   2015-04-10 09:21:00
有了 解構的是return的S沒錯 謝謝各位

Links booklink

Contact Us: admin [ a t ] ucptt.com