如果函數沒有傳回值,則函數內部的變數在函數執行結束之後全部釋放;
如果函數有傳回值,則函數內臨時變數在函數所在的指派陳述式執行完畢之後釋放.
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base():selfid(++n)
{
cout<<"Base "<<selfid<<" by default"<<endl;
}
Base(const Base& other):selfid(++n)
{
cout<<"Base "<<selfid<<" by copy from "<<other.selfid<<endl;
}
Base& operator=(const Base& other)
{
cout<<"Base "<<selfid<<" by = from "<<other.selfid<<endl; return *this;
}
virtual ~Base()
{
cout<<"Base "<<selfid<<" destroyed"<<endl;
}
private:
int selfid;
static n;
};
int Base::n=0;
Base Test()
{
return Base();
}
int main()
{
Base b1;
b1=Test();
return 0;
}
從這裡可以看出,函數Test內的b2,的釋放是發生在指派陳述式b1=Test()之後進行的
你能說出這裡至少兩處合理性嗎?因為如果提前釋放,指派陳述式找不到賦值的來源.
如果函數沒有傳回值,則函數內部的變數在函數執行結束之後全部釋放;
如果函數有傳回值,則函數內臨時變數在函數所在的指派陳述式執行完畢之後釋放.
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
Base():selfid(++n)
{
cout<<"Base "<<selfid<<" by default"<<endl;
}
Base(const Base& other):selfid(++n)
{
cout<<"Base "<<selfid<<" by copy from "<<other.selfid<<endl;
}
Base& operator=(const Base& other)
{
cout<<"Base "<<selfid<<" by = from "<<other.selfid<<endl; return *this;
}
virtual ~Base()
{
cout<<"Base "<<selfid<<" destroyed"<<endl;
}
private:
int selfid;
static n;
};
int Base::n=0;
Base Test()
{
return Base();
}
int main()
{
Base b1;
b1=Test();
return 0;
}
從這裡可以看出,函數Test內的b2,的釋放是發生在指派陳述式b1=Test()之後進行的
你能說出這裡至少兩處合理性嗎?因為如果提前釋放,指派陳述式找不到賦值的來源.