how to write a delete()

C

cmk128

Hi
class A
{
};

class B
{
public:
static void* operator new(size_t sz, A &a)
{
return ::new char[sz];
}
static void operator delete(void* p, A &a)
{
::delete p;
}
};

A a;
B *p = new(a) B();
delete p, a; <---------------- How to write a delete like this?

thanks
from Peter ([email protected])
 
V

Victor Bazarov

Hi
class A
{
};

class B
{
public:
static void* operator new(size_t sz, A &a)
{
return ::new char[sz];
}
static void operator delete(void* p, A &a)
{
::delete p;
}
};

A a;
B *p = new(a) B();
delete p, a; <---------------- How to write a delete like this?

There is no way. Unfortunately there is no "placement delete" syntax.
Search the archives for any discussions about it.

V
 
D

Dave Rahardja

Hi
class A
{
};

class B
{
public:
static void* operator new(size_t sz, A &a)
{
return ::new char[sz];
}
static void operator delete(void* p, A &a)
{
::delete p;
}
};

A a;
B *p = new(a) B();
delete p, a; <---------------- How to write a delete like this?

thanks
from Peter ([email protected])

You can't.

operator delete(void*) [or operator delete(void*, std::size_t)] is _always_
called when you call delete. You can't pass parameters to the delete call.

You probably want to store a reference to A in B's constructor, so you can use
it for deletion later on.

See "Effective C++" Item 52, and the standard 3.7.3.2/2.

-dr
 
J

James Kanze

class A
{
};

class B
{
public:
static void* operator new(size_t sz, A &a)
{
return ::new char[sz];
}
static void operator delete(void* p, A &a)
{
::delete p;
}
};
A a;
B *p = new(a) B();
delete p, a; <---------------- How to write a delete like this?

As others have pointed out, you can't. The usual solution is
for the operator new to allocate some extra, hidden memory, and
store the address of the allocator it was passed there. (Be
careful of alignment issues if you do this.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,120
Latest member
ShelaWalli
Top