本文介绍了Singleton Implementation的任何内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我多次见过, //周四: 等级T { public: static T * instance(); private: T(){} ~T(){} 静态T * smInstance; }; // T.cpp : T * T :: smInstance = NULL; T * T :: instance() { if(smInstance == NULL) smInstance = new T(); 返回smInstance; } 但我怀疑有内存泄漏,因为有一个free()调用 为new()分配的内存。 然而,我多次看到我倾向于怀疑自己 - 一个类似的 实现甚至出现在c ++ cook book上,这是一本非常新的书。 O''really。 任何人都可以帮忙澄清一下吗?谢谢。 I saw it many times, // T.h: class T{public:static T* instance();private:T() {}~T() {}static T* smInstance;}; // T.cpp: T* T::smInstance = NULL; T* T::instance(){if (smInstance == NULL)smInstance = new T(); return smInstance;} But I suspected there is a memory leak, because there is a free() callfor the memory allocated by new(). However, I saw it many times that I tend to doubt myself - a similiarimplementation even appears on the "c++ cook book", a very new book byO''really. Anybody can help to clarify? Thanks. 推荐答案 我认为你的意思更像是: 模板< class T> class Singleton { // ... }; 它''如果您的程序永远不会停止运行或者操作系统 在您之后清理,那么这不是内存泄漏,其中一个可能在所有现代的b $ b系统中都是正确的。查看_Modern C ++ Design_的第6章,比以往任何时候都要多。 想知道如何用C ++实现单例。 干杯! --M I think you mean something more like: template<class T>class Singleton{// ...}; It''s not a memory leak if your program never stops running or if the OScleans up after you, one of which is probably true on all modernsystems. See chapter 6 of _Modern C++ Design_ for more than you everwanted to know about implementing singletons in C++. Cheers! --M 什么时候smInstance解构了? Ben Pope - 我不只是一个数字。对很多人来说,我被称为字符串... When is smInstance deconstructed? Ben Pope--I''m not just a number. To many, I''m known as a string... 这篇关于Singleton Implementation的任何内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-16 17:08