Boost logo

Boost Users :

From: Graham Reitz (graham.cpp_at_[hidden])
Date: 2007-04-02 21:54:30


I was toying with the example in "Beyond the C++ Standard Library An
Introduction to Boost", Library 3:Utility. Specifically, the section on
using checked_delete(). On page 85 it mentions that, "It can be easy to get
into this kind of trouble with smart pointers". I tried the example
presented with raw and shared_ptr. The destructor doesn't get called with
the raw pointer example (the undefined behavior) but when using shared_ptr
with the same example the destructor gets called.

What was the author (Bjorn Karlsson) referring to when he mentioned this can
be an issue with smart pointers?

Thanks,
Graham

Code:

// to_be_deleted.h
#include <iostream>

class to_be_deleted
{
public:
    ~to_be_deleted()
    {
        std::cout << "Help me get called.\n";
    }
};

// deleter.h
#include "boost/shared_ptr.hpp"

class to_be_deleted;
using namespace boost;

class deleter
{
public:
    //void delete_it(shared_ptr<to_be_deleted> p);
    void delete_it(to_be_deleted* p);
};

// deleter.cpp
#include "deleter.h"
#include "boost/checked_delete.hpp"

void deleter::delete_it(to_be_deleted* p)
//void deleter::delete_it(shared_ptr<to_be_deleted> p)
{
    delete p;
    //boost::checked_delete(p);
}

// main.cpp
#include "boost/shared_ptr.hpp"
#include "deleter.h"
#include "to_be_deleted.h"

using namespace boost;

// Forces the type being deleted to be known at compile time

int main(int argc, char* argv[])
{
    {
        //shared_ptr<to_be_deleted> p(new to_be_deleted());
        to_be_deleted* p = new to_be_deleted;
        deleter d;
        d.delete_it(p);
    }

    return 0;
}



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net