c++临时对象

临时对象通常产生于以下4种情况:

  1. 类型隐式转换
  2. 按值传递
  3. 按值返回
  4. 对象定义(A())

<1>. 在使用一个临时对象( 可能是无名对象 或者 返回对象值时 ) 创建构造另一个对象的过程的中,c++会优化掉该临时对象的产生,直接以相同参数调用相关构造函数构或者 直接调用拷贝构造函数 到 目标对象.

     

<2>. 若不是对象创建,而是对象赋值,则在赋值表达式的右值处的临时对象

      创建不能省略,临时对象赋值给左值后,表达式结束,临时对象被析构。

#include"stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator> 
#include <string>
using namespace std;
class A
{
public:
	A(){cout<<"constructor!"<<endl;};
	~A(){cout<<"destroy!"<<endl;};
	A(const A& B){cout<<"copy constructor!"<<endl;	}
	A func(){return *this;};
};
int main()
{
	A a;
	A b;
	b=a.func();
    
	int aa;
	cin>>aa;
	return 0;
}

class B
{
public:
	B(int i){cout<<"B construct!"<<endl;};
	~B(){cout<<"B destruct!"<<endl;};
};
class A
{
public:
	A(B){cout<<"constructor!"<<endl;};
	~A(){cout<<"destroy!"<<endl;};
	A(const A& B){cout<<"copy constructor!"<<endl;	}
	A func(){return *this;};
};
int main()
{
	A(3);
	//A b;
	//b=a.func();
    
	int aa;
	cin>>aa;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值