基本知识: http://www.cs.virginia.edu/~evans/cs216/guides/x86.html
#include <iostream>
using namespace std;
/*Function to return struct */
struct A
{
int ma;
int mb;
int mc;
int md;
int me;
};
struct A fun(void)
{
struct A a1;
a1.ma = 1;
a1.mb = 2;
a1.mc = 3;
a1.md = 4;
a1.me = 5;
return a1;
}
//the asm code struct A fun(void) { 00411370 push ebp 00411371 mov ebp,esp //设定函数栈起始地址 00411373 sub esp,54h //预留空间给局部变量 00411376 push ebx 00411377 push esi 00411378 push edi struct A a1; a1.ma = 1; 00411379 mov dword ptr [a1],1 a1.mb = 2; 00411380 mov dword ptr [ebp-10h],2 a1.mc = 3; 00411387 mov dword ptr [ebp-0Ch],3 a1.md = 4; 0041138E mov dword ptr [ebp-8],4 a1.me = 5; 00411395 mov dword ptr [ebp-4],5 return a1; //以下部分代码,将a1 拷贝到 ebp+8指定地址的一块区域里 0041139C mov eax,dword ptr [ebp+8] 0041139F mov ecx,dword ptr [a1] 004113A2 mov dword ptr [eax],ecx 004113A4 mov edx,dword ptr [ebp-10h] 004113A7 mov dword ptr [eax+4],edx 004113AA mov ecx,dword ptr [ebp-0Ch] 004113AD mov dword ptr [eax+8],ecx 004113B0 mov edx,dword ptr [ebp-8] 004113B3 mov dword ptr [eax+0Ch],edx 004113B6 mov ecx,dword ptr [ebp-4] 004113B9 mov dword ptr [eax+10h],ecx //设定返回值放置的地址 004113BC mov eax,dword ptr [ebp+8] } //函数返回 弹出栈 004113BF pop edi 004113C0 pop esi 004113C1 pop ebx 004113C2 mov esp,ebp 004113C4 pop ebp 004113C5 ret
class B
{
public:
B() { cout << "hello"<<endl;}
B(B& b) { i = b.i;cout << "hello"<<endl;}k
~B() {cout << "bye" <<endl;}
int i;
};
/*Function to return class */
B fun2(void)
{
B b;
b.i = 1;
return b;
}
B fun2(void) { 004113E0 push ebp //设定函数栈起始地址(也称基址) 004113E1 mov ebp,esp 004113E3 push 0FFFFFFFFh 004113E5 push offset __ehhandler$?fun2@@YA?AVB@@XZ (413A91h) 004113EA mov eax,dword ptr fs:[00000000h] 004113F0 push eax 004113F1 mov dword ptr fs:[0],esp //预留局部变量地址 004113F8 sub esp,48h 004113FB push ebx 004113FC push esi 004113FD push edi //不知道这个ebp-54h这个变量是干什么用的。 004113FE mov dword ptr [ebp-54h],0 B b; //压入this 指针,调用构造函数。 00411405 lea ecx,[b] 00411408 call B::B (4110C8h) 0041140D mov dword ptr [ebp-4],1 b.i = 1; //给i 赋值1 00411414 mov dword ptr [b],1 return b; //在调用函数栈上创建一个临时对象 //ebp+8存放着临时对象的起始地址 //并调用拷贝构造函数 0041141B lea eax,[b] 0041141E push eax 0041141F mov ecx,dword ptr [ebp+8] 00411422 call B::B (4111B8h) 00411427 mov ecx,dword ptr [ebp-54h] 0041142A or ecx,1 0041142D mov dword ptr [ebp-54h],ecx 00411430 mov byte ptr [ebp-4],0 //调用b 的析构函数 00411434 lea ecx,[b] 00411437 call B::~B (411113h) 0041143C mov eax,dword ptr [ebp+8] } 0041143F mov ecx,dword ptr [ebp-0Ch] 00411442 mov dword ptr fs:[0],ecx 00411449 pop edi 0041144A pop esi 0041144B pop ebx 0041144C mov esp,ebp 0041144E pop ebp 0041144F ret
int main(int argc,char *agrv[])
{
//test the struct return
struct A a2;
a2 = fun();
//test class return and initialize the class variable
B b2= fun2();
//test class return and assign the class variable
B b3;
b3 = fun2();
return 0;
}