473,322 Members | 1,421 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,322 software developers and data experts.

new vs new[1]

Hello,

Why do i can't write "new [1]" instead of "new" everywhere in
applications? So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.

Or application performance will be significantly reduced?

Thanks,
Denis.

Jul 26 '06 #1
10 3423
"Denis Petronenko" <pe********@gmail.comschrieb im Newsbeitrag
news:11**********************@75g2000cwc.googlegro ups.com...
Hello,

Why do i can't write "new [1]" instead of "new" everywhere in
applications? So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.

Or application performance will be significantly reduced?
You can, but then you could also use the default constructor of such
objects. You'd have to replace simple code like

std::string* pstr = new std::string("Some string");

by something like

std::string* pstr = new std::string;
*pstr = "Some string";

and that might indeed reduce performance. Also, if you kow what you are
doing and the names of your variables are well chosen, you should easily
know when to use delete and when to use delete[].

And just in case that would be too difficult to handle, don't use new[] at
all. Use std::vector instead a C style array.

You should also consider using a RAII approach to handle memory allocation.
Write a wrapper class for pointers to single objects (or use std::auto_ptr)
and a similiar wrapper for pointers to arrays. Once you get used to it, you
don't have to worry about delete at all.

HTH
Heinz

Jul 26 '06 #2
In article <11**********************@75g2000cwc.googlegroups. com>,
"Denis Petronenko" <pe********@gmail.comwrote:
Why do i can't write "new [1]" instead of "new" everywhere in
applications? So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.
It would simplify coding more if you only called 'new' instead of
'new[]', and used std::vector wherever you used to use 'new[]'
Or application performance will be significantly reduced?
I doubt it.
Jul 26 '06 #3

Denis Petronenko wrote:
Why can't I write "new [1]" instead of "new" everywhere in
applications?
You can. Try it.
So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.

Or application performance will be significantly reduced?
Not significantly. However, new[1] will allocate extra space to save
the number 1. It's not uncommon to save 4 bytes. Also, delete[]
will be a bit slower because it uses a loop to call the dtor once.

The reason for the distinction is that these are low-level building
blocks, not intended for direct use. With smart pointers, you don't
need to call delete at all. (and with std::vector you don't call
delete[])

HTH,
Michiel Salters.

Jul 26 '06 #4
Denis Petronenko posted:
Hello,

Why do i can't write "new [1]" instead of "new" everywhere in
applications? So, i will not need to track where i must call delete and
where delete[]. Therefore, it will simplify coding.

Or application performance will be significantly reduced?

I actually used it once to *increase* performance one time:

#include <cstddef>

template<class T, std::size_t len>
struct DefInitArray {
T array[len];
DefInitArray() : array() {}
};

#include <cstring>
#include <ostream>
#include <cstdlib>
#include <iostream>

class StringStream {
protected:

enum { buflen = 1024U };
char *const pbuf;
char *pos;

public:

StringStream() :

/* LOOK AT THE FOLLOWING LINE */
pbuf( (new DefInitArray<char,buflen>[1])->array ),
pos( pbuf ) {}

StringStream(StringStream const &original) :
pbuf(new char[buflen]),
pos( pbuf + (original.pos - original.pbuf) )
{
std::memcpy(pbuf, original.pbuf, sizeof *pbuf * buflen);
}

StringStream &operator=(StringStream const &rhs)
{
std::memcpy(pbuf, rhs.pbuf, sizeof *pbuf * buflen);

pos = pbuf + (rhs.pos - rhs.pbuf);

return *this;
}

bool IsFull() const
{
return pos == pbuf + (buflen - 1);
}

StringStream &operator<<(char const c)
{
if( !IsFull() ) *pos++ = c;

return *this;
}

StringStream &operator<<(const char *p)
{
for( ; *p; ++p) *this << *p;

return *this;
}

void Print( std::ostream &out ) const
{
out << pbuf << '\n';
}

~StringStream()
{
delete [] pbuf;

/* Instead of this, I would have
needed something like.

normal_new ? delete pbuf : delete [] pbuf;

"normal_new" would have to be
a member object. Perhaps:

bool normal_new;

*/
}
};

--

Frederick Gotham
Jul 26 '06 #5
Frederick Gotham posted:
I actually used it once to *increase* performance one time:
I should have mentioned that that wasn't "real" code of mine -- there are
plenty of places where I would have taken the efficiency wrench to it.

--

Frederick Gotham
Jul 26 '06 #6

"Frederick Gotham" <fg*******@SPAM.comwrote in message
news:6K*******************@news.indigo.ie...
Frederick Gotham posted:
>I actually used it once to *increase* performance one time:

I should have mentioned that that wasn't "real" code of mine -- there are
plenty of places where I would have taken the efficiency wrench to it.
pbuf( (new DefInitArray<char,buflen>[1])->array ),
What's "buflen>[1]" supposed to signify?

-Howard

Jul 26 '06 #7

"Howard" <al*****@hotmail.comwrote in message
news:nR********************@bgtnsc04-news.ops.worldnet.att.net...
>
"Frederick Gotham" <fg*******@SPAM.comwrote in message
news:6K*******************@news.indigo.ie...
>Frederick Gotham posted:
>>I actually used it once to *increase* performance one time:

I should have mentioned that that wasn't "real" code of mine -- there are
plenty of places where I would have taken the efficiency wrench to it.

>pbuf( (new DefInitArray<char,buflen>[1])->array ),

What's "buflen>[1]" supposed to signify?
D'oh!!! I missed the matching < before that, sorry. (What's the smiley for
a shameful face?)

-H


Jul 26 '06 #8
Howard wrote:
D'oh!!! I missed the matching < before that, sorry. (What's the smiley
for a shameful face?)
http://en.wikipedia.org/wiki/Emoticon#Basic_examples
Jul 26 '06 #9
Frederick Gotham wrote:
...
I actually used it once to *increase* performance one time:
...
template<class T, std::size_t len>
struct DefInitArray {
T array[len];
DefInitArray() : array() {}
};
...
class StringStream {
protected:

enum { buflen = 1024U };
char *const pbuf;
char *pos;

public:

StringStream() :

/* LOOK AT THE FOLLOWING LINE */
pbuf( (new DefInitArray<char,buflen>[1])->array ),
pos( pbuf ) {}
...
~StringStream()
{
delete [] pbuf;

/* Instead of this, I would have
needed something like.

normal_new ? delete pbuf : delete [] pbuf;

"normal_new" would have to be
a member object. Perhaps:

bool normal_new;

*/
}
Firstly, this looks like a workaround for a compiler non-compliance
issue. Normally, there wouldn't be any need for that 'DefInitArray'
dealie, because in C++ 'new[]' does naturally accept the '()'
initializer. So, you could've just said

StringStream() :
pbuf( new char[buflen]() ),
pos( pbuf ) {}

Secondly, formally this is a hack that leads to undefined behavior in
the destructor. The type used in your 'new[]' was
'DefInitArray<char,buflen>'. That means that the argument of the
'delete[]'s shall have 'DefInitArray<char,buflen>*' type, not 'char*'
type. I.e. formally you still need some kind of branching in the destructor.

--
Best regards,
Andrey Tarasevich
Jul 26 '06 #10
Andrey Tarasevich posted:
Firstly, this looks like a workaround for a compiler non-compliance
issue. Normally, there wouldn't be any need for that 'DefInitArray'
dealie, because in C++ 'new[]' does naturally accept the '()'
initializer. So, you could've just said

StringStream() :
pbuf( new char[buflen]() ),
pos( pbuf ) {}

I wasn't aware you could do that. I'll use it in my future code :).

Secondly, formally this is a hack that leads to undefined behavior in
the destructor. The type used in your 'new[]' was
'DefInitArray<char,buflen>'. That means that the argument of the
'delete[]'s shall have 'DefInitArray<char,buflen>*' type, not 'char*'
type. I.e. formally you still need some kind of branching in the
destructor.

Damn it I hadn't considered that.

--

Frederick Gotham
Jul 26 '06 #11

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

Similar topics

1
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. In fact there...
3
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. I am...
5
by: | last post by:
Hi all, I've been using C++ for quite a while now and I've come to the point where I need to overload new and delete inorder to track memory and probably some profiling stuff too. I know that...
2
by: Dave | last post by:
Hello all, I'd like to find a source on the web that discusses, in a comprehensive manner and in one place, everything about new / delete. It should include overloading operator new, the new...
15
by: Steve | last post by:
I have a form with about 25 fields. In the BeforeUpdate event of the form, I have code that sets the default value of each field to its current value. For a new record, I can put the focus in any...
7
by: Mike Bulava | last post by:
I have created a base form that I plan to use throughout my application let call the form form1. I have Built the project then add another form that inherits from form1, I add a few panel controls...
7
by: Sakharam Phapale | last post by:
Hi All, How to preserve the old font properties while changing new one? I posted same question 2 months back, but I had very small time then. eg. "Shopping for" is a text in RichTextBox and...
0
by: Ben | last post by:
module main ... application.run(new splashform) .. end module after a few screen, I try to load a new codes I got from MSDN on datagrid that works on its own. I took out submain and ran...
3
by: Grizlyk | last post by:
Hi, people. Can anybody explain me "multiple 'new' at single line" behavior. Consider: p::p(void*); p::p(void*,void*); new A( p(new B), p( new C(p(new D), p(new E)) ), p(new F));
4
by: rgparkins | last post by:
Hello I am running out of time with a problem I have running PHP 5.04 and Apache 2.0 and really need help :(. I have a page that stores a variable in session but each time I reload that page the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.