Hello there,

>From what I understand, if one uses placement new with a parameter to 
>initialize a class, and if that class' constructor throws an exception, then a 
>matching delete operator is called to release the memory. 

This does not seem to work if the overloaded delete operator is a template 
function.

I wrote a test program as follows:

== code ==
#include <stdio.h>
#include <stdlib.h>

class MyClass
{
public:
  MyClass() { throw 1; } // constructor throws exception
};

class Pool1
{
public:
  void *Alloc(size_t size) {
    printf("Pool1::Alloc()\n");
    return malloc(size);
  }
        
  void Free(void *p) {
    printf("Pool1::Free()\n");
    return free(p);
  }
};

template<typename T>
class Pool2
{
public:
  void *Alloc(size_t size) {
    printf("Pool2::Alloc()\n");
    return malloc(size);
  }
        
  void Free(void *p) {
    printf("Pool2::Free()\n");
    return free(p);
  }
};

inline void *operator new(size_t size,Pool1& pool)
{
  return pool.Alloc(size);
}

inline void operator delete(void *p,Pool1& pool)
{
  return pool.Free(p);
}

template<typename T>
inline void *operator new(size_t size,Pool2<T>& pool)
{
  return pool.Alloc(size);
}

template<typename T>
inline void operator delete(void *p,Pool2<T>& pool)
{
  return pool.Free(p);
}

int main (int argc, char * const argv[]) {
  Pool1 pool1;
  Pool2<int> pool2;
        
  try {
    MyClass *myclass = new (pool1) MyClass(); // OK!
  } catch(...) { }
        
  try {
    MyClass *myclass = new (pool2) MyClass(); // delete not called!
  } catch(...) { }
        
  return 0;
}

== end code ==

The output I get is:
Pool1::Alloc()
Pool1::Free()
Pool2::Alloc()

on gcc 4.2.4 (Ubuntu Hardy Heron) and gcc 4.0.1 Mac OS X.

The expected output is:
Pool1::Alloc()
Pool1::Free()
Pool2::Alloc()
Pool2::Free()

as produced with Visual Studio.

Is the usage of the delete operator as a template function incorrect or is this 
a bug?

Thanks for the help!

Reply via email to