469,964 Members | 1,645 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,964 developers. It's quick & easy.

Two C++ questions

Pat
Hi,

1. Any faster method (other than for-loop) to initialize array?

2. Does there have similar C++ function to replace C's "fprintf"?

Thanks.

Pat
Jul 22 '05 #1
45 2161

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Hi,

1. Any faster method (other than for-loop) to initialize array?

2. Does there have similar C++ function to replace C's "fprintf"?

Thanks.

Pat


1) yes, depends which type of array you have though, e.g. char array, array
of ints/etc. or array of classes.

2) not exactly, fprintf is available in C++ using the <cstdio> header, or
you can use an fstream.

Allan
Jul 22 '05 #2

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Hi,

1. Any faster method (other than for-loop) to initialize array?

C++ does not specify the speed of any operation. If you want to know which
of two methods is faster the only way is to try both and time them.

2. Does there have similar C++ function to replace C's "fprintf"?


It does not have a function as such, it has a whole library for doing output
called the iostream library. Here's a quick sample that writes a line to a
file called fred.txt.

ofstream output_file("fred.txt");
output_file << "a number " << 123 << '\n';

john
Jul 22 '05 #3
Pat
Thanks.

I want to initialize "int" and "double" arrays. In my program, they are very
big, more than 10000 entries.

Pat

"John Harrison" <jo*************@hotmail.com> 秎ン
news:c6************@ID-196037.news.uni-berlin.de い级糶...

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Hi,

1. Any faster method (other than for-loop) to initialize array?

C++ does not specify the speed of any operation. If you want to know which
of two methods is faster the only way is to try both and time them.

2. Does there have similar C++ function to replace C's "fprintf"?


It does not have a function as such, it has a whole library for doing

output called the iostream library. Here's a quick sample that writes a line to a
file called fred.txt.

ofstream output_file("fred.txt");
output_file << "a number " << 123 << '\n';

john

Jul 22 '05 #4

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Thanks.

I want to initialize "int" and "double" arrays. In my program, they are very big, more than 10000 entries.

Pat

Are the arrays dynamically allocated, on the stack or global?

Are they constant size?

Does you want to initialise with a single value, with calculated values,
with values read from a file, what exactly?

All these details matter, so I can't say what I would do until I know a bit
more. Even then what I would do isn't necessarily the fastest way, even if
it were fastest on my system, it might not be fastest on your system.

Undoubtedly the fastest way is to initialise an array is to get the compiler
to do it for you, but whether this is possible or not depends on the details
like those I mentioned above.

John

"John Harrison" <jo*************@hotmail.com> 秎ン
news:c6************@ID-196037.news.uni-berlin.de い级糶...

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Hi,

1. Any faster method (other than for-loop) to initialize array?


C++ does not specify the speed of any operation. If you want to know which of two methods is faster the only way is to try both and time them.

2. Does there have similar C++ function to replace C's "fprintf"?


It does not have a function as such, it has a whole library for doing

output
called the iostream library. Here's a quick sample that writes a line to a file called fred.txt.

ofstream output_file("fred.txt");
output_file << "a number " << 123 << '\n';

john


Jul 22 '05 #5
Pat
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.

Pat.

"John Harrison" <jo*************@hotmail.com> 秎ン
news:c6************@ID-196037.news.uni-berlin.de い级糶...

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com...
Thanks.

I want to initialize "int" and "double" arrays. In my program, they are very
big, more than 10000 entries.

Pat


Are the arrays dynamically allocated, on the stack or global?

Are they constant size?

Does you want to initialise with a single value, with calculated values,
with values read from a file, what exactly?

All these details matter, so I can't say what I would do until I know a

bit more. Even then what I would do isn't necessarily the fastest way, even if
it were fastest on my system, it might not be fastest on your system.

Undoubtedly the fastest way is to initialise an array is to get the compiler to do it for you, but whether this is possible or not depends on the details like those I mentioned above.

John

"John Harrison" <jo*************@hotmail.com> 秎ン
news:c6************@ID-196037.news.uni-berlin.de い级糶...

"Pat" <Pa*@Pat.com> wrote in message news:40********@rain.i-cable.com... > Hi,
>
> 1. Any faster method (other than for-loop) to initialize array?
>

C++ does not specify the speed of any operation. If you want to know which of two methods is faster the only way is to try both and time them.
> 2. Does there have similar C++ function to replace C's "fprintf"?
>

It does not have a function as such, it has a whole library for doing output
called the iostream library. Here's a quick sample that writes a line
to a file called fred.txt.

ofstream output_file("fred.txt");
output_file << "a number " << 123 << '\n';

john



Jul 22 '05 #6
Hi,

try the following:
const int SIZE = 10000;
int *iArray = new int[ SIZE ];

...

memset( iArray, 0, SIZE * sizeof( int ) );

to initialize with 0.

"Pat"
wrote in message: <40**********@rain.i-cable.com>
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.

Pat.

"John Harrison" 秎ン
news:c6************@ID-196037.news.uni-berlin.de い级糶...

"Pat" wrote in message news:40********@rain.i-cable.com...
> Thanks.
>
> I want to initialize "int" and "double" arrays. In my program, they are

very
> big, more than 10000 entries.
>
> Pat
>


Are the arrays dynamically allocated, on the stack or global?

Are they constant size?

Does you want to initialise with a single value, with calculated values,
with values read from a file, what exactly?

All these details matter, so I can't say what I would do until I know a

bit
more. Even then what I would do isn't necessarily the fastest way, even if
it were fastest on my system, it might not be fastest on your system.

Undoubtedly the fastest way is to initialise an array is to get the

compiler
to do it for you, but whether this is possible or not depends on the

details
like those I mentioned above.

John

> "John Harrison" 秎ン
> news:c6************@ID-196037.news.uni-berlin.de い级糶...
> >
> > "Pat" wrote in messagenews:40********@rain.i-cable.com... > > > Hi,
> > >
> > > 1. Any faster method (other than for-loop) to initialize array?
> > >
> >
> > C++ does not specify the speed of any operation. If you want to know

which
> > of two methods is faster the only way is to try both and time them.
> >
> >
> > > 2. Does there have similar C++ function to replace C's "fprintf"?
> > >
> >
> > It does not have a function as such, it has a whole library for doing
> output
> > called the iostream library. Here's a quick sample that writes a line

to
a
> > file called fred.txt.
> >
> > ofstream output_file("fred.txt");
> > output_file << "a number " << 123 << '\n';
> >
> > john
> >
> >
>
>



Jul 22 '05 #7
Pat wrote:
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.


You might want to look up memset() which is probably the fastest
way you can set a range of memory to repetitions of the same byte.
Someone gave an example already. This method is however hardly
useful for anything other than filling with zeroes or some other
byte-sized value (so if your L is greater than 255 or if the
array is not of ints, forget memset).

You may also gain some time using memcpy() which is used to
copy ranges of memory, if it suits your example. Both these
functions are quite ugly and low-level, but that's what you're
looking for, right?

HTH,
- J.
Jul 22 '05 #8

"Pat" <Pa*@Pat.com> wrote in message news:40**********@rain.i-cable.com...
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.

Pat.


I would use fill_n.

#include <algorithm>

std::fill_n(array, SIZE, value);

Works on int arrays and double arrays and any other sort of array. The other
possibility is memset for filling an int array with zero.

john
Jul 22 '05 #9
John Harrison wrote:

"Pat" <Pa*@Pat.com> wrote in message news:40**********@rain.i-cable.com...
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.
[snip] The other
possibility is memset for filling an int array with zero.


My understanding is that you shouldn't be using any mem* function on _anything_
allocated w/ new.
Jul 22 '05 #10
Julie wrote:

My understanding is that you shouldn't be using any mem* function on _anything_
allocated w/ new.


Is that really the case? If so, I have some code to fix :).
Can someone confirm it and explain the rationale behind it?

TIA,
- J.
Jul 22 '05 #11
Jacek Dziedzic <ja*************@janowo.net> wrote in
news:c6**********@korweta.task.gda.pl:
Julie wrote:

My understanding is that you shouldn't be using any mem* function on
_anything_ allocated w/ new.


Is that really the case? If so, I have some code to fix :).
Can someone confirm it and explain the rationale behind it?


By using the mem* family of functions on classes, you may be catching
implementation-specific pieces of your class, such as a potential 'vtable
pointer' that your implementation may use. By doing a memset(this, 0,
sizeof(*this));, you may whack that vtable pointer, and who knows what's
gonna happen when you then try to call a virtual function.....

Or, there may be other RTTI stuff in the memory space of the class. Who
knows.
Jul 22 '05 #12
"Julie" <ju***@nospam.com> wrote
John Harrison wrote:

"Pat" <Pa*@Pat.com> wrote
John,

Initially, these arrays are allocated by "new". After some operations, I
want to re-initialize the arrays to a initial value, say L. They are
constant size.
[snip]
The other possibility is memset for filling an int array with zero.


My understanding is that you shouldn't be using any mem* function on

_anything_ allocated w/ new.


You shouldn't use mem*() on non-POD objects, regardless of how or where they're
allocated. There's nothing wrong with using mem*() functions on POD objects (or
arrays thereof), even if they're allocated with 'new'. Still, given a choice,
it's better to use the standard algorithms.

Claudio Puviani
Jul 22 '05 #13
Pat
Thanks all of you.

Pat

"Pat" <Pa*@Pat.com> 秎ン news:40********@rain.i-cable.com い级糶...
Hi,

1. Any faster method (other than for-loop) to initialize array?

2. Does there have similar C++ function to replace C's "fprintf"?

Thanks.

Pat

Jul 22 '05 #14
Andre Kostur wrote:
Jacek Dziedzic <ja*************@janowo.net> wrote in
news:c6**********@korweta.task.gda.pl:

Julie wrote:
My understanding is that you shouldn't be using any mem* function on
_anything_ allocated w/ new.


Is that really the case? If so, I have some code to fix :).
Can someone confirm it and explain the rationale behind it?

By using the mem* family of functions on classes, you may be catching
implementation-specific pieces of your class, such as a potential 'vtable
pointer' that your implementation may use. By doing a memset(this, 0,
sizeof(*this));, you may whack that vtable pointer, and who knows what's
gonna happen when you then try to call a virtual function.....

Or, there may be other RTTI stuff in the memory space of the class. Who
knows.


No, not _classes_, I'd never erase a _class_ with memset. But
Julie suggested you can't use mem*() on _anything_ created with
new. Is this really the case that doing something like

int *p=new int[1000000];
memset(p,0,sizeof(int)*1000000);

is a bad idea just because p was allocated with new?

- J.
Jul 22 '05 #15
>
No, not _classes_, I'd never erase a _class_ with memset. But
Julie suggested you can't use mem*() on _anything_ created with
new. Is this really the case that doing something like

int *p=new int[1000000];
memset(p,0,sizeof(int)*1000000);

is a bad idea just because p was allocated with new?

- J.


No, Julie was mistaken.

john
Jul 22 '05 #16
Claudio Puviani wrote:

You shouldn't use mem*() on non-POD objects, regardless of how or where they're
allocated. There's nothing wrong with using mem*() functions on POD objects (or
arrays thereof), even if they're allocated with 'new'. Still, given a choice,
it's better to use the standard algorithms.


Unfortunately, at least in my implementation, clearing an 400MB array
array via memset() is faster than std::fill_n() by a factor of five.
Of course it's ugly and allows for filling with certain values only.

- J.
Jul 22 '05 #17
Claudio Puviani wrote:

You shouldn't use mem*() on non-POD objects, regardless of how or where they're
allocated. There's nothing wrong with using mem*() functions on POD objects (or
arrays thereof), even if they're allocated with 'new'. Still, given a choice,
it's better to use the standard algorithms.


Now, that is some relief :). I've erased many an int array via memset
and most of these had been allocated by new. Glad I won't have to fix
that :).

Thanks for making it clear,
- J.
Jul 22 '05 #18
John Harrison wrote:

No, not _classes_, I'd never erase a _class_ with memset. But
Julie suggested you can't use mem*() on _anything_ created with
new. Is this really the case that doing something like

int *p=new int[1000000];
memset(p,0,sizeof(int)*1000000);

is a bad idea just because p was allocated with new?

- J.


No, Julie was mistaken.

john


I'd like to see something from the standard that explicitly states that POD
types allocated by new can be manipulated w/ mem* functions.

How about a struct of PODs, what is the 'rule' in that case.

Regardless of what the answer is, I'd say that this is a definite case of 'bad
style'. If you are going to use mem* functions, allocate the memory w/ malloc
and friends.
Jul 22 '05 #19
Claudio Puviani wrote:

"Julie" <ju***@nospam.com> wrote
John Harrison wrote:

"Pat" <Pa*@Pat.com> wrote
> John,
>
> Initially, these arrays are allocated by "new". After some operations, I
> want to re-initialize the arrays to a initial value, say L. They are
> constant size.

[snip]
The other possibility is memset for filling an int array with zero.


My understanding is that you shouldn't be using any mem* function on

_anything_
allocated w/ new.


You shouldn't use mem*() on non-POD objects, regardless of how or where they're
allocated. There's nothing wrong with using mem*() functions on POD objects (or
arrays thereof), even if they're allocated with 'new'. Still, given a choice,
it's better to use the standard algorithms.

Claudio Puviani


This just stinks of bad design.

If you are going to use mem* functions, allocate the memory w/ malloc.

If you are going to use the std functions, allocate the memory w/ new.
Jul 22 '05 #20
Julie <ju***@nospam.com> wrote in news:40***************@nospam.com:
John Harrison wrote:
>
> No, not _classes_, I'd never erase a _class_ with memset. But
> Julie suggested you can't use mem*() on _anything_ created with
> new. Is this really the case that doing something like
>
> int *p=new int[1000000];
> memset(p,0,sizeof(int)*1000000);
>
> is a bad idea just because p was allocated with new?
>
> - J.


No, Julie was mistaken.

john


I'd like to see something from the standard that explicitly states
that POD types allocated by new can be manipulated w/ mem* functions.

How about a struct of PODs, what is the 'rule' in that case.

Regardless of what the answer is, I'd say that this is a definite case
of 'bad style'. If you are going to use mem* functions, allocate the
memory w/ malloc and friends.


Um, section 3.9.3 talks about POD types being memcpyable.... (and it
makes no distinction on _where_ the pointer came from, only that they
exist and are valid....)
Jul 22 '05 #21
On Tue, 27 Apr 2004 08:44:42 -0700, Julie <ju***@nospam.com> wrote:
This just stinks of bad design.

If you are going to use mem* functions, allocate the memory w/ malloc.
Why? malloc and new do much the same thing for POD types (although I'm
not suggesting you mix them!). And what's wrong with ::operator new?
What if you want to use a custom global version of new?
If you are going to use the std functions, allocate the memory w/ new.


What, std functions like std::memset?

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #22
"Julie" <ju***@nospam.com> wrote
Claudio Puviani wrote:
You shouldn't use mem*() on non-POD objects, regardless of how or where they're allocated. There's nothing wrong with using mem*() functions on POD objects (or arrays thereof), even if they're allocated with 'new'. Still, given a choice, it's better to use the standard algorithms.
This just stinks of bad design.


It has nothing to do with design. It's an implementation detail.
If you are going to use mem* functions, allocate the memory w/ malloc.
There's no need whatsoever in C++ to use malloc/free, except to support legacy
code. new/delete should be used.
If you are going to use the std functions, allocate the memory w/ new.


The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated. It's very important for you to make a clear distinction
in your mind about that because if you don't, you'll stub your toes when you
start dealing with more advanced forms of memory management.

Whether you have a block of memory that's allocated on the heap, in free store,
on the stack, or in static space, that block of memory can be manipulated
equally well with mem* functions, standard algorithms, or plain old pointers.
In fact, if you need to copy rad bytes across storage classes, you don't have a
choice but to violate your arbitrary rule:

static char inStatic[100];

void func()
{
char onStack[100];
char *withNew = new char[100];
char *withMalloc = (char *)malloc(100); // deprecated

memcpy(onStack, withNew, 100); // perfectly valid
std::copy(withNew, withNew+100, onStack); // equally valid

memcpy(onStack, inStatic, 100); // perfectly valid
std::copy(inStatic, inStatic+100, onStack); // equally valid

memcpy(onStack, withMalloc, 100); // perfectly valid
std::copy(withMalloc, withMalloc+100, onStack); // equally valid

memcpy(withNew, withMalloc, 100); // perfectly valid
std::copy(withMalloc, withMalloc+100, withNew); // equally valid

// and so on
}

I can't stress this enough: memory allocation and operations on allocated
memory are orthogonal. That's why C++ decouples allocation/deallocation from
object construction/destruction.

Claudio Puviani
Jul 22 '05 #23

"Andre Kostur" <nn******@kostur.net> wrote in message
news:Xn*******************************@207.35.177. 134...
Julie <ju***@nospam.com> wrote in news:40***************@nospam.com:
John Harrison wrote:

>
> No, not _classes_, I'd never erase a _class_ with memset. But
> Julie suggested you can't use mem*() on _anything_ created with
> new. Is this really the case that doing something like
>
> int *p=new int[1000000];
> memset(p,0,sizeof(int)*1000000);
>
> is a bad idea just because p was allocated with new?
>
> - J.

No, Julie was mistaken.

john


I'd like to see something from the standard that explicitly states
that POD types allocated by new can be manipulated w/ mem* functions.

How about a struct of PODs, what is the 'rule' in that case.

Regardless of what the answer is, I'd say that this is a definite case
of 'bad style'. If you are going to use mem* functions, allocate the
memory w/ malloc and friends.


Um, section 3.9.3 talks about POD types being memcpyable.... (and it
makes no distinction on _where_ the pointer came from, only that they
exist and are valid....)


And footnote 37 says that the intent of POD types is that they are
compatible with C.

I don't think this question of how the object is allocate is an issue, if
memset is usable on POD types and not usable on non-POD types it going to be
so regardless of how that type was allocated.

john
Jul 22 '05 #24
Claudio Puviani wrote:
If you are going to use the std functions, allocate the memory w/ new.


The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated.


You don't allocate memory w/ new, you allocate space for instances of objects,
be they classes or POD types.

malloc is the only way to allocate 'memory'.

mem* functions are for manipulating memory.
Jul 22 '05 #25
Claudio Puviani wrote:
There's no need whatsoever in C++ to use malloc/free, except to support legacy
code. new/delete should be used.


Explain to me how you reallocate a block to a smaller size using new w/o
copying?

I would have contemplated adding the following to the C++ language to
accommodate the allocation of (uninitialized) raw blocks of memory:

void * p = new void[size_in_bytes];

Then it would be possible to make the very real distinction between memory and
instance allocation.
Jul 22 '05 #26
"Julie" <ju***@nospam.com> wrote
Claudio Puviani wrote:
If you are going to use the std functions, allocate the memory w/ new.
The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it should be manipulated.


You don't allocate memory w/ new, you allocate space for instances of

objects, be they classes or POD types.

malloc is the only way to allocate 'memory'.

mem* functions are for manipulating memory.
You seriously need to hit the books again. Comments like these will make you
lose any credibility you may have had in this newsgroup.
I would have contemplated adding the following to the C++ language to
accommodate the allocation of (uninitialized) raw blocks of memory:

void * p = new void[size_in_bytes];

Then it would be possible to make the very real distinction between memory and instance allocation.


C++ simply requires that you phrase it differently:

void * p = new char[size_in_bytes];

If you honestly believe that 'p' doesn't point to memory after this operation,
it's hopeless.

Claudio Puviani
Jul 22 '05 #27
Julie wrote:
Claudio Puviani wrote:
If you are going to use the std functions, allocate the memory w/ new.


The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated.

You don't allocate memory w/ new, you allocate space for instances of objects,
be they classes or POD types.

malloc is the only way to allocate 'memory'.

mem* functions are for manipulating memory.


What do you think "space" means in this context? How does it differ
from "memory?"
Jul 22 '05 #28
Claudio Puviani wrote:

"Julie" <ju***@nospam.com> wrote
Claudio Puviani wrote:
> If you are going to use the std functions, allocate the memory w/ new.

The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it should be manipulated.
You don't allocate memory w/ new, you allocate space for instances of

objects,
be they classes or POD types.

malloc is the only way to allocate 'memory'.

mem* functions are for manipulating memory.


You seriously need to hit the books again. Comments like these will make you
lose any credibility you may have had in this newsgroup.


You are absolutely right, I do need to continue studying C++ and programming
topics in general -- I'll *never* get to the point that I can say that I'm
done.

Aside from that, credibility in this forum has little to no value w/ me, so
I'll continue to make comments as I see them, be they right or wrong. I have
no problem being wrong, often am, and learn from each and every thread that I'm
involved in.

My statements reflect my treatment of the disparate allocation schemes.
Perhaps I should have phrased it as "I get in less trouble if I consider new as
an allocator of objects, and malloc as an allocator of raw memory".

Personally, I have very little use for malloc, and as you point out, typically
use it for legacy systems or where/when I'm interfacing w/ the operating system
where raw memory is required. I realize that new char[n] allocates memory, and
that no constructor is called for POD types, but I just find it more confusing
to have separate behaviors for new depending on whether or not the allocation
is for a POD type or a non-POD type. I feel sorry for new learners that have
to learn about the different allocation schemes, as well as learn about the
differences between the special class types.
I would have contemplated adding the following to the C++ language to
accommodate the allocation of (uninitialized) raw blocks of memory:

void * p = new void[size_in_bytes];

Then it would be possible to make the very real distinction between memory and
instance allocation.


C++ simply requires that you phrase it differently:


Right -- but it isn't at all clear what is really intended -- is it intended
that you are allocating space for a block of characters -- or -- are you
allocating a block of raw memory for some (non-char) specific purpose? Using
new char[], you can't determine that w/o careful examination of the context and
comments.

If there were a new void[] construct, it would be be infinitely more clear.
Leave new char[] for allocating space for characters, new void[] for allocating
raw memory. Best part is that there are no *new* keywords, the requirement for
casting the new char[] is eliminated, etc.

void * p = new char[size_in_bytes];

If you honestly believe that 'p' doesn't point to memory after this operation,
it's hopeless.


Of course I *know* that p points to allocated memory, but conceptually (for me)
it is more than just raw bytes, it is allocated space for characters. Using it
for something else (such as raw memory) just seems to break the special
distinction that new implies for allocation.
Jul 22 '05 #29
Jeff Schwab wrote:

Julie wrote:
Claudio Puviani wrote:
If you are going to use the std functions, allocate the memory w/ new.

The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated.

You don't allocate memory w/ new, you allocate space for instances of objects,
be they classes or POD types.

malloc is the only way to allocate 'memory'.

mem* functions are for manipulating memory.


What do you think "space" means in this context? How does it differ
from "memory?"


In this case, they are identical -- I'm speaking conceptually, that for me, it
is easier to consider allocations through new to be reserved for instances of
objects, and allocations through malloc to be raw memory.

Consider this:

class Base
{
public:
virtual int Override() { return 0; }
int n;
};

class Derived : public Base
{
public:
virtual int Override() { return 1; }
int x;
};

Derived * p = new Derived[15];

Try to explain in simple what p points to, and what you can and can't do w/ the
underlying allocated memory.

Contrast that with:

char * c = new char[15];

and why you can treat it differently.
Jul 22 '05 #30
Julie wrote:
for me, it
is easier to consider allocations through new to be reserved for instances of
objects, and allocations through malloc to be raw memory.
It is good that you're keeping a conceptual line between raw memory and
typed memory. I don't think avoiding "new" for the raw memory is the
clearest way to express this, though. On the rare occasions when I
really want some raw memory, I typedef unsigned char to a type called
Byte, and work with Bytes as my raw memory. I've found type and
variable names the best places in my code to "self-document."

int main ( )
{
typedef unsigned char Byte;

Byte* raw_memory = new Byte[ 100 ];

// Work with raw memory...

delete [ ] raw_memory;
}
Derived * p = new Derived[15];

Try to explain in simple what p points to, and what you can and can't do w/ the
underlying allocated memory.
p points to the first element in an array of Derived objects.
Contrast that with:

char * c = new char[15];
c points to the first element in an array of char.
and why you can treat it differently.


Because Derived is not POD but char is.
Jul 22 '05 #31
On Tue, 27 Apr 2004 11:04:11 -0700, Julie <ju***@nospam.com> wrote:
Claudio Puviani wrote:
> If you are going to use the std functions, allocate the memory w/ new.
The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated.


You don't allocate memory w/ new, you allocate space for instances of objects,
be they classes or POD types.


void* mem = ::operator new(42);
malloc is the only way to allocate 'memory'.


Really!?

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #32
On Tue, 27 Apr 2004 11:29:47 -0700, Julie <ju***@nospam.com> wrote:
Claudio Puviani wrote:
There's no need whatsoever in C++ to use malloc/free, except to support legacy
code. new/delete should be used.


Explain to me how you reallocate a block to a smaller size using new w/o
copying?

I would have contemplated adding the following to the C++ language to
accommodate the allocation of (uninitialized) raw blocks of memory:

void * p = new void[size_in_bytes];

Then it would be possible to make the very real distinction between memory and
instance allocation.


Read up on operator new.

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #33

"Pat" <Pa*@Pat.com> wrote in message news:40**********@rain.i-cable.com...
Thanks all of you.

Pat


Don't talk while we're interrupting!
:-)
Jul 22 '05 #34
Jeff Schwab wrote:

Julie wrote:
for me, it
is easier to consider allocations through new to be reserved for instances of
objects, and allocations through malloc to be raw memory.


It is good that you're keeping a conceptual line between raw memory and
typed memory. I don't think avoiding "new" for the raw memory is the
clearest way to express this, though. On the rare occasions when I
really want some raw memory, I typedef unsigned char to a type called
Byte, and work with Bytes as my raw memory. I've found type and
variable names the best places in my code to "self-document."

int main ( )
{
typedef unsigned char Byte;

Byte* raw_memory = new Byte[ 100 ];

// Work with raw memory...

delete [ ] raw_memory;
}
Derived * p = new Derived[15];

Try to explain in simple what p points to, and what you can and can't do w/ the
underlying allocated memory.


p points to the first element in an array of Derived objects.
Contrast that with:

char * c = new char[15];


c points to the first element in an array of char.


Right! Which, conceptually, should be treated differently than an allocated
block of raw memory.
and why you can treat it differently.


Because Derived is not POD but char is.


Right! I understand that there are special-class types, but feel that it can
be a sticking point for new learners of the language. Personally, I have no
problem w/ it because I stated w/ C and therefore had a basic understanding of
the POD types.

Part of my point is that you have to treat char as a non-POD type AND as an
allocation type for general purpose (raw) memory.

As I've said before, I think of it being more beneficial to think of new as an
allocator of instances of types, and malloc as an allocator of raw (untyped)
memory. My use of malloc is few and far between, so when it does happen, it is
usually very localized or well defined, and I have no problem keeping track of
the allocation scheme.

As I've stated, I would have preferred that new provide a method by which raw
(untyped) memory could be allocated, rather than allocating chars and calling
it raw. I've proposed

void * p = new void[size_in_bytes];

as reasonable candidate for such, although I realize that no such beast will be
making it into the standard, nor is this the forum to discuss such features.
Jul 22 '05 #35
tom_usenet wrote:

On Tue, 27 Apr 2004 11:04:11 -0700, Julie <ju***@nospam.com> wrote:
Claudio Puviani wrote:
> If you are going to use the std functions, allocate the memory w/ new.

The two concepts are COMPLETELY unrelated. There is nothing practical or
theoretical that correlates how and where memory is allocated with the way it
should be manipulated.
You don't allocate memory w/ new, you allocate space for instances of objects,
be they classes or POD types.


void* mem = ::operator new(42);


I was not aware of this usage of new. Thank you for pointing it out.

I ammend my comments:

Raw memory should be allocated using the method you describe. Raw memory
allocated through new char[size] should be considered 'bad style'.
malloc is the only way to allocate 'memory'.
Really!?


I was talking conceptually. I prefer to consider allocations (excepting your
method above) with new as allocations of instances of object(s).

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html

Jul 22 '05 #36
tom_usenet wrote:

On Tue, 27 Apr 2004 11:29:47 -0700, Julie <ju***@nospam.com> wrote:
Claudio Puviani wrote:
There's no need whatsoever in C++ to use malloc/free, except to support legacy
code. new/delete should be used.


Explain to me how you reallocate a block to a smaller size using new w/o
copying?

I would have contemplated adding the following to the C++ language to
accommodate the allocation of (uninitialized) raw blocks of memory:

void * p = new void[size_in_bytes];

Then it would be possible to make the very real distinction between memory and
instance allocation.


Read up on operator new.


Done, thanks for pointing that out.

Regardless, I personally think that the intention of new void[] is somewhat
more clear, but this isn't the forum for such discussions.
Jul 22 '05 #37
On Wed, 28 Apr 2004 08:38:28 -0700, Julie <ju***@nospam.com> wrote:
I ammend my comments:

Raw memory should be allocated using the method you describe. Raw memory
allocated through new char[size] should be considered 'bad style'.


Why? The lifetime of a POD object begins when storage of suitable
alignment becomes available. However, there doesn't seem a compelling
reason not to use operator new rather than new char[] - it may be more
efficient (in space) for one.
>malloc is the only way to allocate 'memory'.


Really!?


I was talking conceptually. I prefer to consider allocations (excepting your
method above) with new as allocations of instances of object(s).


You may prefer to consider allocations with new as allocations of
instances of object(s), but for POD types, it is no different from
using malloc or any other memory allocator. You know that of course,
so you're overstating your case somewhat.

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #38
"Julie" <ju***@nospam.com> wrote

I ammend my comments:

Raw memory should be allocated using the method you describe. Raw memory
allocated through new char[size] should be considered 'bad style'.


Oh, for crying out loud! Just what credentials do you have to presume to dictate
style to people who have orders of magnitude more experience and knowledge than
you? So far, I haven't seen the slightest indication that you'd even recognize
good style, let alone be in a position to define it for others. You can say, "I
personally don't like that style," but it's laughable for you to try to define
what "good" style is on the basis of your ignorance of the language and its
idioms.

Claudio Puviani
Jul 22 '05 #39
Claudio Puviani wrote:

"Julie" <ju***@nospam.com> wrote

I ammend my comments:

Raw memory should be allocated using the method you describe. Raw memory
allocated through new char[size] should be considered 'bad style'.
Oh, for crying out loud! Just what credentials do you have to presume to dictate
style to people who have orders of magnitude more experience and knowledge than
you?


I wasn't trying to dictate -- I should have prefaced that with "I prefer to
consider ..."
So far, I haven't seen the slightest indication that you'd even recognize
good style,


I don't know that I've tried to indicate good style, as I usually stay out of
those discussions. Feel free to arrive at whatever conclusion you desire, I'm
not trying to impress you or anyone else on this forum.

Regardless, do you consider the following 'good style' or an 'accepted idiom'?

// allocate raw memory for image bits
void * p = (void *)new char[image_size];

(Note: I'm using C-style casts for brevity, substitute C++ style casts if you
prefer, the underlying idea is the same.)

Personally, I consider that there are more appropriate ways to allocate raw
memory rather than confusing the issue w/ a placeholder type such as char.

Previously, as I've stated, in the past I've used malloc for the allocation of
what I considered raw memory, and new char[] for the allocation of character
arrays. In the future, I'll use ::operator new(size) for allocations of raw
memory, and new char[] for the allocation of characters arrays.
Jul 22 '05 #40
Julie <ju***@nospam.com> wrote in news:40***************@nospam.com:

Regardless, do you consider the following 'good style' or an 'accepted
idiom'?

// allocate raw memory for image bits
void * p = (void *)new char[image_size];

(Note: I'm using C-style casts for brevity, substitute C++ style casts
if you prefer, the underlying idea is the same.)


Um... why cast at all since you get the conversion to void * for free?
Jul 22 '05 #41
Julie <ju***@nospam.com> wrote in message news:<40***************@nospam.com>...
Jeff Schwab wrote:

Julie wrote:
for me, it
is easier to consider allocations through new to be reserved for instances of
objects, and allocations through malloc to be raw memory.


It is good that you're keeping a conceptual line between raw memory and
typed memory. I don't think avoiding "new" for the raw memory is the
clearest way to express this, though. On the rare occasions when I
really want some raw memory, I typedef unsigned char to a type called
Byte, and work with Bytes as my raw memory. I've found type and
variable names the best places in my code to "self-document."

int main ( )
{
typedef unsigned char Byte;

Byte* raw_memory = new Byte[ 100 ];

// Work with raw memory...

delete [ ] raw_memory;
}

Derived * p = new Derived[15];

Try to explain in simple what p points to, and what you can and can't do w/ the
underlying allocated memory.


p points to the first element in an array of Derived objects.
Contrast that with:

char * c = new char[15];


c points to the first element in an array of char.


Right! Which, conceptually, should be treated differently than an allocated
block of raw memory.
and why you can treat it differently.


Because Derived is not POD but char is.


Right! I understand that there are special-class types, but feel that it can
be a sticking point for new learners of the language. Personally, I have no
problem w/ it because I stated w/ C and therefore had a basic understanding of
the POD types.

Part of my point is that you have to treat char as a non-POD type AND as an
allocation type for general purpose (raw) memory.

As I've said before, I think of it being more beneficial to think of new as an
allocator of instances of types, and malloc as an allocator of raw (untyped)
memory. My use of malloc is few and far between, so when it does happen, it is
usually very localized or well defined, and I have no problem keeping track of
the allocation scheme.

As I've stated, I would have preferred that new provide a method by which raw
(untyped) memory could be allocated, rather than allocating chars and calling
it raw. I've proposed

void * p = new void[size_in_bytes];

as reasonable candidate for such, although I realize that no such beast will be
making it into the standard, nor is this the forum to discuss such features.


So if C++ doesn't deal directly with raw memory, then what is
std::raw_memory_iterator for? I thought it was explicitly for
stepping through bytes allocated like:

void *p = new char[user_defined_size];

Dave Moore
Jul 22 '05 #42
Julie wrote:
Regardless of what the answer is, I'd say that this is a definite case of 'bad
style'.
Well, if memset() clears a 1GB array five times faster than
any other method (in my implementation, that is) it's not bad style,
it's efficiency. I'm not one who falls prey to over-optimizing
to gain microseconds, but when we're talking about minutes
(clearing an array within a tight loop), I can't resist using
memset(), if not going for an compiler-specific even-faster
alternative (out of scope of this ng, of course).
If you are going to use mem* functions, allocate the memory w/ malloc
and friends.


Now that I was "made sure" (thanks, John!) that clearing a new'ed
array is perfectly safe, I cannot accept your concept of having to
introduce one ugly-low-level-C'ism whenever I'm forced to use
another ugly-low-level-C'ism -- that's weird. Actually (I have
almost no C background) I cannot imagine a rationale for using
malloc() ever -- is there any? I'd rather use ::new and allocate
char's, at least I don't have to double check it didn't fail.

- J.
Jul 22 '05 #43
Andre Kostur wrote:

Julie <ju***@nospam.com> wrote in news:40***************@nospam.com:
Regardless, do you consider the following 'good style' or an 'accepted
idiom'?

// allocate raw memory for image bits
void * p = (void *)new char[image_size];

(Note: I'm using C-style casts for brevity, substitute C++ style casts
if you prefer, the underlying idea is the same.)


Um... why cast at all since you get the conversion to void * for free?


I was including it for clarity and documentative purposes, making it clear to
the reader that I was deliberately storing in a void *.
Jul 22 '05 #44
Julie <ju***@nospam.com> wrote:
Raw memory allocated through new char[size]
should be considered 'bad style'.


I agree, if you mean that you prefer using std::vector to allocate
raw memory, as guaranteed by C++03:

std::vector<unsigned char> raw(200);
unsigned char *ptr = &raw[0];

This has the advantage of cleaning up automatically, and being
able to re-size and preserve the contents in an exception-safe manner.
Jul 22 '05 #45
Jacek Dziedzic wrote:
Julie wrote:
Regardless of what the answer is, I'd say that this is a definite case
of 'bad
style'.

Well, if memset() clears a 1GB array five times faster than
any other method (in my implementation, that is) it's not bad style,
it's efficiency. I'm not one who falls prey to over-optimizing
to gain microseconds, but when we're talking about minutes
(clearing an array within a tight loop), I can't resist using
memset(), if not going for an compiler-specific even-faster
alternative (out of scope of this ng, of course).


Sometimes you have no choice but to throw style to the winds and do some
down and dirty programming to get something to run fast. That should be
the last choice though once you have already done it "nicely" and shown
(through profiling or whatever) that indeed this is a performance
problem spot *in the overall program*. So what if it takes 10 times as
long to initalize some big chunk of memory if that is 1/100,000th of the
run time of the program? Oft times people get lost in writing ugly code
to speed things up when in the end it doesn't actually make the program
run much faster.

Even then you should explain exactly WHAT and (more importantly) WHY you
are doing it so that when the next poor schmuck who comes along and has
to maintain your code isn't totally misled.
Jul 22 '05 #46

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

reply views Thread by softwareengineer2006 | last post: by
reply views Thread by connectrajesh | last post: by
8 posts views Thread by Krypto | last post: by
reply views Thread by ramu | last post: by
1 post views Thread by ramu | last post: by
reply views Thread by ramu | last post: by
1 post views Thread by rainxy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.