基于book , 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 neat\n";
return true;
}
int main() {
function1<bool,const std::string&> f1(&some_function);
f1(std::string("Hello"));
}
问题> invoker_base
的默认析构函数不是虚拟的。 function1
的实现是否存在内存泄漏?如代码所示,function1::~function1
通过非虚拟基类指针删除分配的资源。
最佳答案
这里没有内存泄漏(对象不拥有任何需要delete
-ing 的资源)。
但是,在没有虚拟析构函数的情况下通过指向基的指针在非基对象上调用 delete
会导致未定义的行为。
关于c++ - 基于非虚拟模板的类 - 泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8695225/