Sunday, February 27, 2011

The differences among auto_ptr, scoped_ptr and shared_ptr



#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <stdio.h>

#include "Int.h" // include 4 bytes int class

typedef std::auto_ptr<Int>     auto_ptr;
typedef boost::scoped_ptr<Int> scoped_ptr;
typedef boost::shared_ptr<Int> shared_ptr;

void size()
{
  printf("sizeof(auto_ptr)   is %d\n", sizeof(auto_ptr));   // 4
  printf("sizeof(scoped_ptr) is %d\n", sizeof(scoped_ptr)); // 4
  printf("sizeof(shared_ptr) is %d\n", sizeof(shared_ptr)); // 8
}

void foo_ptr(auto_ptr ap)
{
  ap->foo();
}

void foo_ptr(scoped_ptr scp)
{
  scp->foo();
}

void foo_ptr(shared_ptr shp)
{
  shp->foo();
}

void foo()
{
  {
    //
    // auto_ptr
    //
    Int* pi = new Int(5);
    auto_ptr ap(pi);

    foo_ptr(ap);     // compile ok
    ap->foo();       // runtime error
  }

  {
    //
    // scoped_ptr
    //
    Int* pi = new Int(5);
    scoped_ptr scp(pi);

    // foo_ptr(scp); // compile error
    scp->foo();      // runtime ok
  }

  {
    //
    // scoped_ptr
    //
    Int* pi = new Int(5);
    shared_ptr shp(pi);
foo_ptr(shp);    // compile ok
    shp->foo();      // runtime ok
  }
}

int main()
{
  size();
  foo();
}

Download source code : http://sites.google.com/site/gilgildownload/download/IntTest2.zip

2 comments:

Unknown said...

the auto_ptr is deprecation from C++0x.

use unique_ptr.

unique_ptr is superset of auto_ptr, and safe

gilgil said...

Thank you, Lyn. :)