Mixing new/delete and operator new/delete?

J

Jef Driesen

Is it allowed by the C++ standard to mix the use of 'new/delete' and
'operator new/delete'?

(a) alloc (version 1) + free (version 2)
(b) alloc (version 2) + free (version 1)


// VERSION 1 ALLOC (using operator new + placement new)
type* data = (type*)operator new(n * sizeof(type));
for (type* p = data; p != data + n; ++p)
new ((void *)p) value_type();

// VERSION 1 FREE (using calling destructor + operator delete)
for (type* p = data; p != data + n; ++p)
p->~type();
operator delete(data);

// VERSION 2 ALLOC (using new)
type* data = new type[n];

// VERSION 2 FREE (using delete)
delete [] data;
 
G

Gernot Frisch

Jef Driesen said:
Is it allowed by the C++ standard to mix the use of 'new/delete' and
'operator new/delete'?

(a) alloc (version 1) + free (version 2)
(b) alloc (version 2) + free (version 1)


// VERSION 1 ALLOC (using operator new + placement new)
type* data = (type*)operator new(n * sizeof(type));
for (type* p = data; p != data + n; ++p)
new ((void *)p) value_type();

// VERSION 1 FREE (using calling destructor + operator delete)
for (type* p = data; p != data + n; ++p)
p->~type();
operator delete(data);

// VERSION 2 ALLOC (using new)
type* data = new type[n];

// VERSION 2 FREE (using delete)
delete [] data;

I can imagine it might now cause much problems, as new and delete
internally call malloc, however I would not rely on that + there is no
rule this has to be so. Thus, this can crash badly.
-Gernot
 

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
474,197
Messages
2,571,041
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top