基于非虚拟模板的类泄漏内存
non-virtual template based class - leak memory?
根据书,pp338
#include <iostream>
#include <vector>
#include <string>
#include <ostream>
#include <algorithm>
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <boost/cast.hpp>
using namespace std;
template <typename R, typename Arg> class invoker_base {
public:
virtual R operator()(Arg arg)=0;
};
template <typename R, typename Arg> class function_ptr_invoker
: public invoker_base<R,Arg> {
R (*func_)(Arg);
public:
function_ptr_invoker(R (*func)(Arg)):func_(func) {}
R operator()(Arg arg) {
return (func_)(arg);
}
};
template <typename R, typename Arg> class function1 {
invoker_base<R,Arg>* invoker_;
public:
function1(R (*func)(Arg)) :
invoker_(new function_ptr_invoker<R,Arg>(func)) {}
R operator()(Arg arg) {
return (*invoker_)(arg);
}
~function1() {
delete invoker_;
}
};
bool some_function(const std::string& s) {
std::cout << s << " This is really neatn";
return true;
}
int main() {
function1<bool,const std::string&> f1(&some_function);
f1(std::string("Hello"));
}
Question> invoker_base
的默认析构函数不是虚函数。在function1
的实现中是否存在内存泄漏?如代码所示,function1::~function1
通过非虚拟基类指针删除分配的资源。
这里没有内存泄漏(对象不拥有任何需要delete
-ing的资源)。
但是,通过指向基的指针而不使用虚析构函数在非基对象上调用delete
会导致未定义行为。
别担心:没有内存泄漏!然而,您应该担心的是您调用了未定义的行为。啊,好吧,这可能表现为内存泄漏,但它也可以以任何其他方式表现出来。规则非常简单:如果在静态类型与动态类型不匹配的指针上调用delete,就会有未定义的行为。请注意,未定义的行为通常意味着它可以完美地工作,但当有大笔资金面临风险时,它就会失败,例如,当客户准备同意数百万美元的交易时,如果这一个演示有效-它不会。
相关文章:
- C++功能泄漏内存,我是C++新手,不确定如何解决
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 析构函数 C++ 使泄漏内存
- 构造函数对象赋值是否泄漏内存
- corba :: orb_init泄漏内存
- Gmock泄漏内存
- 如何在不泄漏内存的情况下删除链接列表
- Visual C ODBC关闭记录集泄漏内存
- 为什么泄漏内存比在动态数组上执行 delete[] 慢
- OpenGL正在泄漏内存.哪个对象未释放
- 可以std ::退出泄漏内存
- uiautomation findall泄漏内存
- 为什么在此OpenCL代码中泄漏内存,为什么要泄漏内存
- pthread在完成后会泄漏内存
- win32 标准::线程泄漏内存
- 返回指向同一变量的指针是否会泄漏内存
- 使用clectType(new any_type())可能会泄漏内存泄漏
- Windows开发:如何确定我的应用程序是否正在泄漏内存
- WinHttp打开泄漏内存