背景知识1:
class ABCD
{
public:
ABCD(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
printf("ABCD() construct, a:%d,b:%d,c:%d \n" , this-> a, this ->b, this-> c);
}
~ ABCD()
{
printf("~ABCD() construct,a:%d,b:%d,c:%d \n" , this-> a, this ->b, this-> c);
}
int getA ()
{
return this ->a;
}
protected:
private:
int a ;
int b ;
int c ;
};
int run3 ()
{
printf("run3 start..\n" );
ABCD(400, 500, 600); //ABCD是类名,没有声明对象,直接调用此时则生成匿名对象
printf("run3 end\n" );
return 0;
}
int main ()
{
run3();
system("pause" );
return 0;
}
ABCD是类名,没有声明对象,直接调用此时则生成匿名对象
但是为什么先析构,后面才出现run3 end?
这就说明了,函数还没有结束,就先析构了,换句话说,匿名对象,在执行完他的功能后立即就会被回收(并不像其他临时变量,要在函数执行完回收)
背景知识2:
上述run3()替换为:
int run3 ()
{
printf("run3 start..\n" );
ABCD abcd = ABCD(100, 200, 300);
printf("run3 end\n" );
return 0;
}
则结果变成:
这说明匿名对象直接转为,对象abcd,然后在函数结束之后析构
转化验证:
class Test03
{
public :
Test03 ()
{
cout << "ooo我在无参构造 this= " << this<< endl ;
}
Test03 (const Test03 & C )
{
cout << "ooo我在进行拷贝构造 this= " << this << endl ;
}
Test03 (int _a, int _b)
{
cout << "ooo我在有参构造 this= " << this << endl ;
}
~ Test03 ()
{
cout << "ooo我在析构 this= " << this << endl ;
}
void OutThis ()
{
cout << " 我的this= " << this << endl ;
}
};
Test03 g ()
{
Test03 A (1, 2);
return A ;
}
void shiyan ()
{
cout << "实验开始" << endl;
Test03 B = g(); //g()生成的匿名对象直接转化为B,来提高效率
B .OutThis ();
Test03 C ;
C = g ();
C .OutThis ();
cout << "实验结束" << endl;
}
void main ()
{
shiyan ();
system ("pause" );
}
匿名对象强化:
class MyTest
{
public:
MyTest(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
printf("MyTest:%d, %d, %d\n" , a, b, c);
}
MyTest(int a, int b)
{
this->a = a;
this->b = b;
MyTest(a , b, 100); //注
printf("MyTest:%d, %d\n" , a, b);
}
~ MyTest()
{
printf("~MyTest:%d, %d, %d\n" , a, b, c);
}
protected:
private:
int a ;
int b ;
int c ;
public:
int getC () const { return c ; }
};
int main ()
{
MyTest t1 (1, 2);
printf("c:%d" , t1.getC()); //请问c的值是?
system("pause" );
return 0;
}
这里标“注”的地方是重点
在执行 MyTest(a , b, 100); 时 其实只是生成了匿名对象,会重新分配一块内存,所以这里支队新生成的匿名对象中的c进行操作,并且会在使用完匿名对象后立即析构。所以是
所以会在 printf(“MyTest:%d, %d\n” , a, b);这句执行前就析构了,而且本类中的c并没有被赋值,所以c还是乱码