Re: delete in-place corresponding to placement new?

From: Rob Williscroft (rtw_at_freenet.REMOVE.co.uk)
Date: 02/29/04


Date: 29 Feb 2004 22:13:33 GMT

Peter Olcott wrote in
news:OFs0c.119804$hR.2308785@bgtnsc05-news.ops.worldnet.att.net:

> I have just built a class that provides the most useful subset of
> std::vector functionality for use by compilers that lack template
> capability.
>
> http://home.att.net/~olcott/std_vect.html
>
> Through suggestions from this news group I was able to exactly
> duplicate the interface of std::vector, except for one aspect. What I
> need is a way to invoke the destructor on elements of an array without
> de-allocating the memory of this array. This would correspond to
> placement new, constructing without allocating. The most obvious way
> that comes to mind is to merely explicitly invoke the destructor. This
> capability is not available on a circa 1990 compiler. Does anyone have
> any good ideas?
>

Assuming that you can't do:

template < typename T >
inline void destroy( T *t )
{
  t->~T();
}

Then you could try:

#define OFFSETOFF( Class, Member ) \
   (((char *)&((Class *)0)->Member) - ((char *)0))

template < class T >
struct cheat_detor
{
  T item;

  inline void operator delete (void *) {}

  static void destroy( T *ptr )
  {
    delete (
      (cheat_detor< T > *)
        (((char *)ptr) - OFFSETOFF( cheat_detor< T >, item ))
    );
  }
};

template < class T >
inline void destroy( T * ptr )
{
  cheat_detor< T >::destroy( ptr );
}

The above is non-standard code, infact g++ will issue a warning
if T is a non-POD type say:

struct X
{
  X() {}
  ~X() {}
};

Rob.

-- 
http://www.victim-prime.dsl.pipex.com/


Relevant Pages

  • Re: Access Violation Releasing CComPtr
    ... You're using COM objects from DllMain (global destructors are ... TerminateProcess) which doesn't invoke ... msxml3.dll!DOMDocumentWrapper::`vector deleting destructor'() + ... hDllHandle=0x0dea0000, unsigned long dwReason=0x00000000, void * ...
    (microsoft.public.platformsdk.security)
  • Re: delete []
    ... when invoke delete, the destructor for each instance element of the ... , I malloc 10 bytes, and in the destructor of this class I will ... So the memory is balanced, ...
    (microsoft.public.dotnet.languages.vc)
  • derived method of abstract base class not getting invoked
    ... Code to invoke: ... saying there is no source code available. ... Since this is debug compiled code I assume the compiler is responsible ... I should add that I had the same problem with the base destructor, ...
    (microsoft.public.vc.language)
  • Re: More on garbage collection
    ... >>> If you have to invoke a destructor, ... > That doesn't work if the object references itself, ... > point a reference-counted garbage collector will not know it should ...
    (comp.arch)