惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
量子位
G
Google Developers Blog
J
Java Code Geeks
N
Netflix TechBlog - Medium
博客园 - 聂微东
宝玉的分享
宝玉的分享
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
月光博客
月光博客
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
雷峰网
雷峰网
M
MIT News - Artificial intelligence
T
Tailwind CSS Blog
V
Visual Studio Blog
阮一峰的网络日志
阮一峰的网络日志
博客园 - 三生石上(FineUI控件)
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
有赞技术团队
有赞技术团队
T
The Blog of Author Tim Ferriss

博客园 - 张瓅

puppy-language ConsolePlayer 仙剑奇侠传4主题曲 QBASIC代码 HTML5 编译期运算 如何测量代码执行时间 【转】老外眼中的武侠小说 1850年的宁波 关于安装 DirectX SDk Dec 2005 后无法编译DirectShow应用程序的问题 [转]VB中嵌入汇编与真正的DLL 新的连连看网络版 各种连接字符串 关于CSS属性display:none和visible:hidden的区别 我用超白痴的方法解出了这道题,大家有没有更好的方法 Fire Net 尝试了一下Flex VFP中如何调用API函数 DES加密算法的实现 软件项目经理必备素质(转)
模版调用析构函数的一个发现
张瓅 · 2006-11-19 · via 博客园 - 张瓅

假如我这样写:
int *a = new i;
a->~int();
肯定无法通过编译,因为基本类型是没有析构函数的。
然而我在做内存池时遇到一个问题就是对像释放内存时,需要内存池自动析构该对像然后收回内存空间,但并不知道该对像是不是基本类型。
于是我做了如下的实验:

class A
{
public:
    A()
{};
    
~A(){};
}
;

//相当于一个析构器
template<typename T>
void Deconstructor(T *&p)
{
    p
->~T();
    free(p);
    p 
= NULL;
}


int main()
{
    
int *= new int;
    Deconstructor(i);

    A 
*= new A;
    Deconstructor(a);
}


结果发现编译、运行正常。输出汇编查找原因:
找到“析构”整型的那段。


16   :  p->~T();
17   :  free(p);

 mov eax, DWORD PTR _p$[ebp]
 mov ecx, DWORD PTR [eax]
 push ecx
 call _free
 add esp, 
4


当T为int时编译器根本没有为~T()生成任何代码,这也是编译器的聪明之处吧。