基于非虚拟模板的类泄漏内存

non-virtual template based class - leak memory?

本文关键字:泄漏 内存 于非 虚拟      更新时间:2023-10-16

根据书,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,就会有未定义的行为。请注意,未定义的行为通常意味着它可以完美地工作,但当有大笔资金面临风险时,它就会失败,例如,当客户准备同意数百万美元的交易时,如果这一个演示有效-它不会。