如果函數沒有返回值,則函數內部的變量在函數執行結束之後全部釋放;
如果函數有返回值,則函數內臨時變量在函數所在的賦值語句執行完畢之釋放.
class Object
{
public:
Object() {cout<<"Object"<<endl;}
~Object() {cout<<"Object destroyed"<<endl;}
protected:
private:
};
class Base
{
public:
Base():selfid(n)
{
n++; cout<<"Base "<<selfid<<" by default"<<endl;
}
Base(int a):selfid(n)
{
n++; cout<<"Base "<<selfid<<"by "<<a<<endl;
}
Base(const Base& other):selfid(n)
{
n++; cout<<"Base "<<selfid<<" by copy"<<endl;
}
Base& operator=(const Base& other)
{
cout<<"Base "<<selfid<<" by ="<<endl; return *this;
}
virtual ~Base()
{
n--; cout<<"Base "<<selfid<<" destroyed"<<endl;
}
private:
int selfid;
static n;
};
int Base::n=0;
Base Test(Base b)
{
Object o;
return b;
}
int main()
{
Base b;
Base t=Test(b);
return 0;
}
b:0
Test(b):1
t:2
從這裡可以看出,函數Test內的b,和o的釋放都是發生在賦值語句創建了t之後進行的
你能說出這裡至少兩處合理性嗎?
摘自 ClamReason的專欄