c++ - 基于非虚拟模板的类 - 泄漏内存?

标签 c++

基于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/

相关文章:

c++ - 如何访问私有(private)指向类

c++ - 如何从1000个潜在关键字中确定给定关键字?

c++ - 如何知道 LoadLibrary 加载了哪些依赖项?

c++ - arr[0] 的大小怎么是 8 个字节?

c++ - 链表c++代码错误

c++ - QT中如何将图表保存为图片

c++ - 尝试减小输出大小后,Visual Studio 编译程序无法正确初始化

c++ - 获取回调函数的地址以在C++中动态调用

c++ - 如何:使用 Boost::asio 在线程之间发布消息?

c++ - 在 MSVC 中配置 Qt 项目设置