64,637
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <cstdlib>
using namespace std;
class A
{
public:
A(){cout << "constructor called!" << endl;}
A(int i) : x(i){cout << i << " constructor called!" << endl;}
A(const A &a){cout << x << " copy constructor called!" << endl;}
~A(){cout << x << " destructor called" << endl;}
private:
//A(const A &a){cout << "copy constuctor called!" << endl;}
int x;
};
A get_A()
{
A a(5);
return a;
}
int main()
{
A a = 1;system("pause"); // 1
A b = get_A();system("pause"); // 2
b = a;system("pause"); // 3
A c = A(2);system("pause"); // 4
b = 3;system("pause"); // 5
A d = b;system("pause"); // 6
return 0;
}
void operator = (const A &a)
{
x = a.x;
}
A get_A()
{
return A(5);
}
class B;
class A
{
public:
A(){cout << "constructor called!" << endl;}
A(int i) : x(i){cout << i << " constructor called!" << endl;}
A(const A &a){cout << x << " copy constructor called!" << endl;}
explicit A(const B &b){cout << x << " copy constructor called, via A(const B&)!" << endl;}
~A(){cout << x << " destructor called" << endl;}
private:
//A(const A &a){cout << "copy constuctor called!" << endl;}
int x;
};
class B: public A
{
};
A get_A()
{
A a(5);
return a;
}
int main()
{
A a = 1;//system("pause"); // 1
cout <<endl;
A b = get_A();//system("pause"); // 2
cout <<endl;
b = a;//system("pause"); // 3
cout <<endl;
A c = A(2);//system("pause"); // 4
cout <<endl;
b = 3;//system("pause"); // 5
cout <<endl;
A d = b;//system("pause"); // 6
cout <<endl;
{ // 7
B theb;
A e=theb;
}
cout <<endl;
{ // 8
B theb;
A e(theb);
}
cout <<endl;
system("pause");
return 0;
}
那么第7种情况,这个时候尚须疑虑这里是否有临时变量。因为这里最合适的拷贝构造被explicit了,需要类型转换,(与之对比的第8种情况直接初始化则不然),而细想一下可知,这种转换无须临时变量
出于好奇,我想知道下例第一种情况在你的VS2010上是否也不做返回值优化
class Cls
{
string name;
int m;
public:
Cls(string s,int i):name(s),m(i)
{
cout <<"ctor name=" <<name <<endl;
}
~Cls()
{
cout <<"dtor name=" <<name <<endl;
}
Cls(const Cls& c):m(c.m)
{
cout <<"copy from name=" <<c.name <<" to name=" <<name <<endl;
}
void disp()
{
cout <<"name=" <<name <<" m=" <<m <<endl;
}
void setname(string n)
{
name=n;
}
};
Cls GetCls1(string n,int i)
{
Cls c(n,i); // 局部变量
return c;
}
Cls GetCls2(string n,int i)
{
return Cls(n,i); // 临时变量
}
int main()
{
{
Cls x=GetCls1("x_at_right",3);
x.setname("x_at_left");
x.disp();
}
cout <<endl;
{
Cls y=GetCls2("y_at_right",4);
y.setname("y_at_left");
y.disp();
}
cout <<endl;
{
Cls a("a_as_temp",5);
Cls z=a;
z.setname("z_at_left");
z.disp();
}
cout <<endl;
{
Cls w=Cls("w_at_right",7);
w.setname("w_at_left");
w.disp();
}
cout <<endl;
return 0;
}