64,666
社区成员
发帖
与我相关
我的任务
分享
A a; //c1=1,c2=c3=0,用无参构造器构造
00B916DD lea ecx,[ebp-11h]
00B916E0 call A::A (0B91127h)
00B916E5 mov dword ptr [ebp-4],0
A d = foo(a);
00B916EC push ecx
00B916ED mov ecx,esp
00B916EF mov dword ptr [ebp-0F8h],esp
00B916F5 lea eax,[ebp-11h]
00B916F8 push eax
00B916F9 call A::A (0B911DBh)
00B916FE mov dword ptr [ebp-100h],eax
00B91704 lea ecx,[ebp-1Dh]
00B91707 push ecx
00B91708 call foo (0B91078h)
00B9170D add esp,8
00B91710 mov dword ptr [ebp-104h],eax
00B91716 mov byte ptr [ebp-4],1
#include <iostream>
#include <string>
using namespace std;
int c1=0, c2=0, c3=0;
class A
{
public: A() {c1++;}
A(const A&) {c2++;}
~A() {c3++;}
};
const A foo(const A c)
{
A ab= A(c);
return ab;
}
int main()
{
A a; //c1=1,c2=c3=0,用无参构造器构造
A d = foo(a); //c1=1,c2=3,c3=2,先调用A(const A&),返回时c2=1,然后调用foo(const A c),构造ab之后c2=2,返回ab的时候再次调用A(const A&),此时c2=3,最后析构c3=1
cout <<c1 <<" " <<c2 <<" " <<c3 <<endl;
return 0;
}
class A
{
public: A() {c1++;}
A(const A&) {c2++;}
~A() {c3++;}
};
const A foo(const A c) //传参一次拷贝构造 c2++
{
A ab= A(c); //赋值一次c2++
return ab;
}
int main()
{
A a; //执行一次普通构造 c1=1
A d = foo(a); //结果返回再一次c2++
cout <<c1 <<" " <<c2 <<" " <<c3 <<endl; //在return 0之前,只有函数foo里的c跟ab2个临时变量被析构,c3=2
return 0;
}