用汇编的眼光看C++(之算术符重载陷阱)
【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
在算术符重载里面,“=”重载可能是最经常使用的一种。但是好多人就误以为在函数中,凡是类出现“=”的地方,那就是调用算术符重载,其实不然。为什么呢?我们可以看看下面的代码。首先,我们定义一个基本类:
class data
{
char* value;
int number;
public:
explicit data(int num = 0){
if(num){
number = num;
value = (char*)malloc(num);
}
}
data(const data& d){
number = d.get_number();
value = (char*)malloc(d.get_number());
memmove(value, d.get_point(), d.get_number());
}
~data(){
if(number)
free(value);
}
data& operator=(const data& d){
if(number)
free(value);
number = d.get_number();
value = (char*)malloc(d.get_number());
memmove(value, d.get_point(), d.get_number());
return *this;
}
int get_number() const {return number;}
char* get_point() const {return value;}
};
class data
{
char* value;
int number;
public:
explicit data(int num = 0){
if(num){
number = num;
value = (char*)malloc(num);
}
}
data(const data& d){
number = d.get_number();
value = (char*)malloc(d.get_number());
memmove(value, d.get_point(), d.get_number());
}
~data(){
if(number)
free(value);
}
data& operator=(const data& d){
if(number)
free(value);
number = d.get_number();
value = (char*)malloc(d.get_number());
memmove(value, d.get_point(), d.get_number());
return *this;
}
int get_number() const {return number;}
char* get_point() const {return value;}
};
定义好了函数之后,我们就开始对这个类进行调用,同样代码如下所示:
45: data m(10);
0040108D push 0Ah
0040108F lea ecx,[ebp-14h]
00401092 call @ILT+30(data::data) (00401023)
00401097 mov dword ptr [ebp-4],0
46: data p = m;
0040109E lea eax,[ebp-14h]
004010A1 push eax
004010A2 lea ecx,[ebp-1Ch]
004010A5 call @ILT+35(data::data) (00401028)
004010AA mov byte ptr [ebp-4],1
47: p = m;
004010AE lea ecx,[ebp-14h]
004010B1 push ecx
004010B2 lea ecx,[ebp-1Ch]
004010B5 call @ILT+5(data::operator=) (0040100a)
48: }
45: data m(10);
0040108D push 0Ah
0040108F lea ecx,[ebp-14h]
00401092 call @ILT+30(data::data) (00401023)
00401097 mov dword ptr [ebp-4],0
46: data p = m;
0040109E lea eax,[ebp-14h]
004010A1 push eax
004010A2 lea ecx,[ebp-1Ch]
004010A5 call @ILT+35(data::data) (00401028)
004010AA mov byte ptr [ebp-4],1
47:&
补充:软件开发 , C++ ,