当前位置:编程学习 > C/C++ >>

函数内临时变量的释放时刻

如果函数没有返回值,则函数内部的变量在函数执行结束之后全部释放;

如果函数有返回值,则函数内临时变量在函数所在的赋值语句执行完毕之释放.

 

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的专栏

补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,