从汇编角度理解C++虚函数调用机制

#include <memory>

class Base
{
public:
	virtual void print(){ printf("Base::print()\n");}
	void print2(){}
public:
	int m_id;
};

class Imp : public Base
{
private:
	void print(){ printf("Imp::print()\n");}
};

template<class T>
void swap(T& a, T& b)
{
	T tmp;
	tmp = a;
	a = b;
	b = tmp;
}
int main()
{
	int a = 1, b = 2;
	swap(a, b);
	Base* pBase = new Base();
	Base* pImp = new Imp();
	__asm	// pImp->print()汇编实现(去除那些Debug调试信息)
	{
		mov eax,dword ptr [pImp]	//获取pImp这个指针数据值,可以理解pImp是个整形变量,取整形变量内的值即指针
		mov edx,dword ptr [eax]		//获取pImp第一个数据地址,即虚函数表地址
		mov eax,dword ptr [edx]		//获取虚函数表指针指向的第一个函数指针
		call eax					//调用Imp::print()
	}

	pBase->print();
	pBase->m_id = 5;
	getchar();
	return 0;
}

上面插入的一段汇编就是虚函数调用,可以vs IDE下通过反汇编Alt+8,查看。

1、只要这个类中有虚函数,则此类就有属于自己的虚函数表指针;

2、虚函数表指针隐藏在类的内存数据的最前面4个字节(32位程序,指针长度);

3、虚函数每次调用都需要通过虚函数表指针锁定到指定地址才可以调用。


翻译一下function format = stlGetFormat(fileName) %STLGETFORMAT identifies the format of the STL file and returns 'binary' or %'ascii' fid = fopen(fileName); % Check the file size first, since binary files MUST have a size of 84+(50*n) fseek(fid,0,1); % Go to the end of the file fidSIZE = ftell(fid); % Check the size of the file if rem(fidSIZE-84,50) > 0 format = 'ascii'; else % Files with a size of 84+(50*n), might be either ascii or binary... % Read first 80 characters of the file. % For an ASCII file, the data should begin immediately (give or take a few % blank lines or spaces) and the first word must be 'solid'. % For a binary file, the first 80 characters contains the header. % It is bad practice to begin the header of a binary file with the word % 'solid', so it can be used to identify whether the file is ASCII or % binary. fseek(fid,0,-1); % go to the beginning of the file header = strtrim(char(fread(fid,80,'uchar')')); % trim leading and trailing spaces isSolid = strcmp(header(1:min(5,length(header))),'solid'); % take first 5 char fseek(fid,-80,1); % go to the end of the file minus 80 characters tail = char(fread(fid,80,'uchar')'); isEndSolid = findstr(tail,'endsolid'); % Double check by reading the last 80 characters of the file. % For an ASCII file, the data should end (give or take a few % blank lines or spaces) with 'endsolid <object_name>'. % If the last 80 characters contains the word 'endsolid' then this % confirms that the file is indeed ASCII. if isSolid & isEndSolid format = 'ascii'; else format = 'binary'; end end fclose(fid);
最新发布
05-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值