临时对象通常产生于以下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;
}