boost::scoped_ptr

どっかで new したやつは delete しないとメモリリークする.
で,メモリリークわすれをなくすため,スコープを抜けたときにメモリを開放してくれるようにしたい.ってことで scopred_ptr

// scpptr.cpp
#include <iostream>
#include <string>
#include <algorithm>

#include <boost/scoped_ptr.hpp>

using namespace std;

void call_func(const string& s)
{
  boost::scoped_ptr<string> str(new string(s));

  cout << "Original string: " << *str << endl;
  reverse(str->begin(), str->end());
  cout << "Reverse string : " << *str << endl;
}

int main(int argc, char *argv[])
{
  if (argc != 2) cerr << "error." << endl;

  call_func(argv[1]);

  return 0;
}

こうすると,delete してないけどメモリリークしていない.

% valgrind --leak-check=full ./a.out hoge
==6205== Memcheck, a memory error detector.
==6205== Copyright (C) 2002-2007, and GNU GPL'd, by Julian Seward et al.
==6205== Using LibVEX rev 1854, a library for dynamic binary translation.
==6205== Copyright (C) 2004-2007, and GNU GPL'd, by OpenWorks LLP.
==6205== Using valgrind-3.3.1-Debian, a dynamic binary instrumentation framework.
==6205== Copyright (C) 2000-2007, and GNU GPL'd, by Julian Seward et al.
==6205== For more details, rerun with: -v
==6205== 
Original string: hoge
Reverse string : egoh
==6205== 
==6205== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 1)
==6205== malloc/free: in use at exit: 0 bytes in 0 blocks.
==6205== malloc/free: 3 allocs, 3 frees, 38 bytes allocated.
==6205== For counts of detected errors, rerun with: -v
==6205== All heap blocks were freed -- no leaks are possible.