[cpp] construction fucntion

徐梓鼎 xuziding at gmail.com
Mon Mar 26 10:05:19 CST 2007


我现在想在一个类的构造里面调用另外一个构造函数,我已经只知道可以采用如下
的方法来达到这个目的:
#include <iostream>

class A{
	int m_a;
public:
	//A(){std::cout<< "A()new"; new(this)A(0);}//大概记得这个方法是 TCPL 里面推荐的
	A(){std::cout<< "A()this->A::A()";this->A::A(0);}
	A(int a):m_a(a){std::cout<< "A(int)";}
	int get(){return m_a;}
};

int main()
{
	std::cout << A().get() << "\n" ;
	std::cout << A(1).get() << "\n" ;
	return 0;
};
但是我却注意到这样的编译器生成出来的确是不同的代码(DEBUG模式 VS7.1)其
中的主要不同部分在于:

new(this)A(0);生成的代码                                           this->A::A(0);生成的代码
0041B29A  mov         eax,dword ptr [this]                         0041B285  push        0                            
0041B29D  push        eax                                          0041B287  mov         ecx,dword ptr [this] 
0041B29E  push        4                                            0041B28A  call        A::A (419131h)          
0041B2A0  call        operator new (4191DBh)                       0041B28F  mov         eax,dword ptr [this] 
0041B2A5  add         esp,8 
0041B2A8  mov         dword ptr [ebp-0E0h],eax 
0041B2AE  mov         dword ptr [ebp-4],0 
0041B2B5  cmp         dword ptr [ebp-0E0h],0 
0041B2BC  je          A::A+83h (41B2D3h) 
0041B2BE  push        0    
0041B2C0  mov         ecx,dword ptr [ebp-0E0h] 
0041B2C6  call        A::A (419131h) 
0041B2CB  mov         dword ptr [ebp-0F4h],eax 
0041B2D1  jmp         A::A+8Dh (41B2DDh) 
0041B2D3  mov         dword ptr [ebp-0F4h],0 
0041B2DD  mov         ecx,dword ptr [ebp-0F4h] 
0041B2E3  mov         dword ptr [ebp-0ECh],ecx 
0041B2E9  mov         dword ptr [ebp-4],0FFFFFFFFh 
0041B2F0  mov         eax,dword ptr [this] 
0041B2F3  mov         ecx,dword ptr [ebp-0Ch] 
0041B2F6  mov         dword ptr fs:[0],ecx 


可以看出 new 这种方式多了很多代码,在release模式,开启最大优化的情况下,
new(this)A(0);生成的代码  仍然会比this->A::A(0);生成的代码多几条。

请教各位:

1.我现在想知道在其他的编译器上的结果。
2.为什么new这样的用法他不是直接调用A::A(int)之后就出来而是转了半天(
汇编不好,没看懂)
3.除了这两种办法,还有没有其他办法在一个构造里面调用其他构造?

PS。虽然这个问题是很无聊,可是我真的很想知道为什么,谢谢各位。


													徐梓鼎
													2007.3.26


---------------
找寻BUG中&# 8230;&# 8230;




More information about the Cpp mailing list