473,748 Members | 2,207 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

inconsistent behavior with user-defined new and delete

We all know that a new-expression,

foo* a = new foo() ;

allocates memory for a single foo then calls foo::foo(). And we know
that

void* p = ::operator new(sizeof(foo) ) ;

allocates a sizeof(foo)-sized buffer but does NOT call foo::foo().
So only new-expressions both allocate and initialize. Fair enough.

Now suppose we wish to use a custom memory pool,

my_pool pool ;
foo* a = new(pool) foo() ;

This calls

void* operator new( std::size_t size, my_pool & )
throw(std::bad_ alloc) ;

and then calls foo::foo(). Naturally we also define

void operator delete( void* data, my_pool & ) throw() ;

But how are we going to call our custom delete?

my_pool pool ;
foo* a = new(pool) foo() ;

// compile error
delete(pool) a ;

// calls the default operator delete(), not our delete
delete a ;

// does not call foo::~foo()
::operator delete(a, pool) ;

// is this the idiom, then?
a->~foo() ;
::operator delete(a, pool) ;

There appears to be no such delete-expression to complement the
new-expression. Why the inconsistency? Surely this is an oversight
in the design of C++? In particular I expected "delete(poo l) a" to
work.

To recap, we have a mechanism for default-allocate-then-construct
(no-argument new-expressions) and for destruct-then-default-deallocate
(no-argument delete-expressions). Furthermore, we have a mechanism
for custom-allocate-then-construct (custom new-expressions), but NOT
for destruct-then-custom-deallocate (no custom delete-expressions).

One workaround is to define operator new() and operator delete()
inside foo, but suppose I can't do that. Another workaround is to use

template< typename pool_type, typename T >
void custom_delete( pool_type & pool, T* p )
{
p->~T() ;
pool.deallocate (p, sizeof(T)) ;
}

but this just begs the question of why that should be necessary, i.e.,
why no delete-expressions, i.e. delete(pool) p.

Incidentally this begs a more general question: since a custom
operator new() defined outside of a class will not work with auto_ptr,
one wonders what is the point of such operator new()s. Surely someone
will eventually use auto_ptr with it by accident, wreaking havoc when
the wrong delete is called from auto_ptr::~auto _ptr(). This seems to
suggest that "delete p" should automagically call

void operator delete( void* data, my_pool & ) throw() ;

however that is probably impossible to implement efficiently (relative
to current C++ implementations ). Another option is for the auto_ptr
constructor to take an optional (de)allocator but that relies on
programmers remembering to do so, which doesn't solve the problem but
just moves it around.

#include <iostream>
#include <ostream>

class my_pool
{
} ;

void* operator new( std::size_t size, my_pool & )
throw(std::bad_ alloc)
{
std::cerr << "my_pool operator new" << std::endl ;
return ::operator new(size) ;
}

void operator delete( void* data, my_pool & ) throw()
{
std::cerr << "my_pool operator delete" << std::endl ;
return ::operator delete(data) ;
}

struct foo
{
foo()
{
std::cerr << "foo::foo() " << std::endl ;
}

~foo()
{
std::cerr << "foo::~foo( )" << std::endl ;
}
} ;

int main()
{
my_pool pool ;

foo* a = new(pool) foo() ;

// compile error
//delete(pool) a ;

// calls the default operator delete(), not ours
//delete a ;

// does not call foo::~foo()
//::operator delete(a, pool) ;

// is this the idiom, then?
a->~foo() ;
::operator delete(a, pool) ;

return 0 ;
}

May 30 '07 #1
10 2094
je************* **@yahoo.com wrote :
We all know that a new-expression,

foo* a = new foo() ;

allocates memory for a single foo then calls foo::foo(). And we know
that

void* p = ::operator new(sizeof(foo) ) ;

allocates a sizeof(foo)-sized buffer but does NOT call foo::foo().
So only new-expressions both allocate and initialize. Fair enough.

Now suppose we wish to use a custom memory pool,

my_pool pool ;
foo* a = new(pool) foo() ;

This calls

void* operator new( std::size_t size, my_pool & )
throw(std::bad_ alloc) ;

and then calls foo::foo(). Naturally we also define

void operator delete( void* data, my_pool & ) throw() ;

But how are we going to call our custom delete?
Not possible using the delete operator. However, do note that a
placement delete counterpart for operator new is needed in the case
that an exception is thrown during object construction, in which case
it is automatically called to clean up the memory.
One workaround is to define operator new() and operator delete()
inside foo, but suppose I can't do that. Another workaround is to use

template< typename pool_type, typename T >
void custom_delete( pool_type & pool, T* p )
{
p->~T() ;
pool.deallocate (p, sizeof(T)) ;
}
Another one is to override the global operator delete, where your
placement new somehow associates the allocator with the allocated chunk
of memory, and the delete fetches the appropriate allocator and uses it
to free the memory.

- Sylvester
May 30 '07 #2
On May 30, 10:40 am, Sylvester Hesp <s.hes...@SPAMo isyn.nlwrote:
>
Not possible using the delete operator. However, do note that a
placement delete counterpart for operator new is needed in the case
that an exception is thrown during object construction, in which case
it is automatically called to clean up the memory.

[...]

Another one is to override the global operator delete, where your
placement new somehow associates the allocator with the allocated chunk
of memory, and the delete fetches the appropriate allocator and uses it
to free the memory.
I don't know if this was a misunderstandin g or not, but I wasn't using
placement new. I was using an overloaded operator new(). My
new-expression is "new(pool) foo()", whereas placement new is
"new(&pool) foo()".
May 30 '07 #3
* je************* **@yahoo.com:
On May 30, 10:40 am, Sylvester Hesp <s.hes...@SPAMo isyn.nlwrote:
>Not possible using the delete operator. However, do note that a
placement delete counterpart for operator new is needed in the case
that an exception is thrown during object construction, in which case
it is automatically called to clean up the memory.

[...]

Another one is to override the global operator delete, where your
placement new somehow associates the allocator with the allocated chunk
of memory, and the delete fetches the appropriate allocator and uses it
to free the memory.

I don't know if this was a misunderstandin g or not, but I wasn't using
placement new. I was using an overloaded operator new(). My
new-expression is "new(pool) foo()", whereas placement new is
"new(&pool) foo()".
The misunderstandin g is on your part: you're using placement new.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 30 '07 #4
je************* **@yahoo.com wrote :
On May 30, 10:40 am, Sylvester Hesp <s.hes...@SPAMo isyn.nlwrote:
>>
Not possible using the delete operator. However, do note that a
placement delete counterpart for operator new is needed in the case
that an exception is thrown during object construction, in which case
it is automatically called to clean up the memory.

[...]

Another one is to override the global operator delete, where your
placement new somehow associates the allocator with the allocated chunk
of memory, and the delete fetches the appropriate allocator and uses it
to free the memory.

I don't know if this was a misunderstandin g or not, but I wasn't using
placement new. I was using an overloaded operator new(). My
new-expression is "new(pool) foo()", whereas placement new is
"new(&pool) foo()".
There was no misunderstandin g from my part, any "overloaded operator
new()", as you call it, is called placement new - not only the one that
takes a void* and returns that very pointer ;)

- Sylvester
May 30 '07 #5
On May 30, 11:19 am, "Alf P. Steinbach" <a...@start.now rote:
* jeffjohnson_al. ..@yahoo.com:
I don't know if this was a misunderstandin g or not, but I wasn't using
placement new. I was using an overloaded operator new(). My
new-expression is "new(pool) foo()", whereas placement new is
"new(&pool) foo()".

The misunderstandin g is on your part: you're using placement new.
new(&pool) foo() calls

void* operator new( std::size_t, void* ) throw() ;

new(pool) foo() calls

void* operator new( std::size_t, my_pool & ) throw(bad_alloc ) ;

If both are called "placement new", then how do we differentiate
between them? The former places the object at the given address,
while the latter can do something else entirely.

By attempting to clarify what looked like a misunderstandin g, I've
inadvertently committed a sin of terminology. I hope the discussion
doesn't get sidetracked due of my linguistic immorality.

May 30 '07 #6
je************* **@yahoo.com wrote:
>
new(&pool) foo() calls

void* operator new( std::size_t, void* ) throw() ;

new(pool) foo() calls

void* operator new( std::size_t, my_pool & ) throw(bad_alloc ) ;

If both are called "placement new", then how do we differentiate
between them? The former places the object at the given address,
while the latter can do something else entirely.
The latter does exactly the same thing as the former: it calls an
overloaded version of operator new. The name for that usage is
"placement new."

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
May 30 '07 #7
On May 30, 12:04 pm, Pete Becker <p...@versatile coding.comwrote :
jeffjohnson_al. ..@yahoo.com wrote:
new(&pool) foo() calls
void* operator new( std::size_t, void* ) throw() ;
new(pool) foo() calls
void* operator new( std::size_t, my_pool & ) throw(bad_alloc ) ;
If both are called "placement new", then how do we differentiate
between them? The former places the object at the given address,
while the latter can do something else entirely.

The latter does exactly the same thing as the former: it calls an
overloaded version of operator new. The name for that usage is
"placement new."
Yes, and I've already openly admitted my sin of terminology, the part
which you clipped. I shall admit this once again, even though you may
clip that and correct me again. Please forgive me.

My question is still valid, however. If both are called placement
new, then what do I say when I mean this

new(&buffer) foo() ;

and what do I say when I mean this

new(debug_alloc ) foo() ;

Obviously I can't just say "placement new" for both. In practice,
when one says "placement new", one usually means placing the object at
the given address, i.e. the former. In particular I bet most C++
programmers would say "placement new" for the first one and something
like "new with debug_alloc" for the second one. "Placement new with
debug_alloc" is likely to cause confusion.

If I may assess the situation, it appears that you wish to be pedantic
about what is correct terminology, while I wish to be practical about
what is clear and unambiguous terminology.

May 30 '07 #8
* je************* **@yahoo.com:
On May 30, 12:04 pm, Pete Becker <p...@versatile coding.comwrote :
>jeffjohnson_al ...@yahoo.com wrote:
>>new(&pool) foo() calls
void* operator new( std::size_t, void* ) throw() ;
new(pool) foo() calls
void* operator new( std::size_t, my_pool & ) throw(bad_alloc ) ;
If both are called "placement new", then how do we differentiate
between them? The former places the object at the given address,
while the latter can do something else entirely.
The latter does exactly the same thing as the former: it calls an
overloaded version of operator new. The name for that usage is
"placement new."

Yes, and I've already openly admitted my sin of terminology, the part
which you clipped. I shall admit this once again, even though you may
clip that and correct me again. Please forgive me.

My question is still valid, however. If both are called placement
new, then what do I say when I mean this

new(&buffer) foo() ;

and what do I say when I mean this

new(debug_alloc ) foo() ;

Obviously I can't just say "placement new" for both. In practice,
when one says "placement new", one usually means placing the object at
the given address, i.e. the former. In particular I bet most C++
programmers would say "placement new" for the first one and something
like "new with debug_alloc" for the second one. "Placement new with
debug_alloc" is likely to cause confusion.

If I may assess the situation, it appears that you wish to be pedantic
about what is correct terminology, while I wish to be practical about
what is clear and unambiguous terminology.
Well, it's not a big deal, except there was a misunderstandin g between
you and someone else higher up in the thread.

Yes, the term "placement" stems from the placement usage, placing an
object at (or is it that "in"? correct me!) some pre-existing storage.

If you want you can call the placement new operator from the <new>
header, a pure placement new or the standard library's placement new.

Hth.,

- Alf

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
May 30 '07 #9
On May 30, 5:56 pm, jeffjohnson_al. ..@yahoo.com wrote:

[...]
new(&pool) foo() calls
void* operator new( std::size_t, void* ) throw() ;
new(pool) foo() calls
void* operator new( std::size_t, my_pool & ) throw(bad_alloc ) ;
If both are called "placement new", then how do we differentiate
between them?
With difficulty:-).

In section §5.3.4 (the description of the new operator), the
standard clearly includes both of these under the name
"placement new". In section §18.5.1.3 (the description of the
placement operator new function in the library), it just as
clearly only consideres the first under the term "placement
new".

In the end, I can't think of anything better that "standard
placement new" and "user-defined placement new". But we really
need a different name for the "placement syntax" described in
§5.3.4, since it really is a misnomer.
The former places the object at the given address,
while the latter can do something else entirely.
By attempting to clarify what looked like a misunderstandin g,
I've inadvertently committed a sin of terminology.
Join the club. The authors of the library section of the
standard didn't do any better.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

May 31 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1907
by: Denis S. Otkidach | last post by:
I've noticed that the order of attribute lookup is inconsistent when descriptor is used. property instance takes precedence of instance attributes: >>> class A(object): .... def _get_attr(self): .... return self._attr .... attr = property(_get_attr) .... >>> a=A()
1
2089
by: bk_kl | last post by:
Hi, I think the following behavior of the build in function 'split' is inconsistent. What do you think? >>> "".split() >>> "".split(";")
9
1760
by: Marina | last post by:
Here is the problem. If 2 different properties on the same (or different) control are bound to the same data column, changing the Text property and calling EndCurrentEdit discards the new value. Changing a custom property and calling EndCurrentEdit accepts the new value, stores it in the datasoure and behaves normally. Here is a reproduceable example: First, extend Textbox: Public Class MyTextBox Inherits TextBox
0
1626
by: Itai | last post by:
Background: I have four Web Form pages with respective C# code behind files, all in the same project: localhost/vpath1 Page1.aspx Page2.aspx
1
1807
by: Mossman | last post by:
Hello, I will discuss at a high level what is happening on an ASP.NET web page I developed a year ago in ASP.NET using Visual Studio 2003 and currently support. I have an ASP.NET web page that is broken out into two sections. One section is where a user enters the main infomation around a financial outlook record and the second section is dynamic content that generates a table of values based on the infromation entered in the first...
1
13973
by: James | last post by:
When I ran db2dart to check a database, I got the following warning and error messages. 1.Warning: The database state is not consistent. 2.Warning: Errors reported about reorg rows may be due to the inconsistent state of the database. 3.Found some orphaned extent numbers in a DMS user tablespace. Any advice on how to change database to be consistent and fix orphaned data? Thanks so much!
1
1955
by: Prasoon | last post by:
I have a JSP page on which when print is pressed - Records are fetched on a redirected page and those are to be printed. I use the lines - <script language="javascript"> window.print(); history.back(); </script> to do the same. When browsed from Netscape 4.7, the Resultset page is printed
3
6198
by: Rahul Babbar | last post by:
Hi All, When could be the possible reasons that could make a database inconsistent? I was told by somebody that it could become inconsistent if you " force all the applications to a close on that database and transactions are not committed or rollbacked" I infact, don't believe it, because i suppose when we do a "force
9
1516
by: Lie | last post by:
I've noticed some oddly inconsistent behavior with int and float: Python 2.5.1 (r251:54863, Mar 7 2008, 03:39:23) on linux2 -345 works, but Traceback (most recent call last): File "<stdin>", line 1, in <module>
2
1642
by: Juha Nieminen | last post by:
Paavo Helde wrote: So which compiler is correct, gcc (which only requires bar() to be declared at the point of insantiation of foo()) or comeau? What happens if you just move the bar() function to be before the foo() function in both source files? (It's not like this was critical from the point of view of my original post.)
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9326
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8245
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6076
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4877
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.