473,326 Members | 2,099 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,326 software developers and data experts.

When to use a garbage collector?

Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?

--
Carlo Milanesi
http://digilander.libero.it/carlmila
Jun 27 '08 #1
46 2121
On 10 kesä, 18:30, Carlo Milanesi <carlo.milanesi.no.s...@libero.it>
wrote:
But in which cases it is better to use one technique and in which cases
another?
It's probably a question that has no answer. But I like the
old school delete, because it's transparent, you know exactly
what it's doing and when.
Jun 27 '08 #2
In article <48**********************@news.tiscali.it>,
ca********************@libero.it says...

[ ... ]
Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.
_Some_ gurus -- there are others (who I think qualify as gurus) who are
opposed to the use of garbage collection to varying degrees, or at least
are of the view that its use should be restricted to specific
situations.
But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?
The cost of garbage collection varies based on the type of collector
used. Nearly every garbage collector has a "mark" phase, in which
"live" objects (i.e. those that are still accessible) are marked as
being in use. The cost of this phase is normally about linear on the
number of objects currently accessible to the program.

After that, different garbage collectors work in a number of different
ways. A copying collector copies all those live objects into a
contiguous space in memory, leaving another contiguous free space. This
makes allocations extremely cheap, and the cost of the collection as a
whole is also linear on the number of objects that are accessible.

Other collectors leave the "live" objects where they are, and create
free blocks of all the contiguous chunks of memory in the heap not
currently occupied by live objects. In this case, the cost of the
collection part tends to relate most closely to the number of contiguous
chunks of free memory in the heap.

On the other side, life isn't simple either. Manual memory management
tends to have costs associated most closely with the number of
allocations and frees used. This cost can be mitigated (drastically) in
certain cases, such as allocating a large number of objects of identical
size, or releasing a large number of objects all at the same, if the
allocator is written to allow them to be released together rather than
individually.

That only begins to tell the real story though: much of the cost of
manual allocation/deletion arises when objects are copied. A garbage
collector can (and does) keep track of different pointers that refer to
an object, and only deletes the object when all pointers that give
access to the object are gone. This makes it easy to keep a single
object, and create new pointers/references to that object whenever
needed.

With manual memory management, it's far more common to duplicate the
entire object, so each time the object is used, there's a separate
instance of the object to look at, and each instance has exactly one
owner that's responsible for deleting the object when it's no longer
needed. Allocating space to hold extra copies of the object, and copying
the relevant data into each copy, can take a considerable amount of
time. With a GC in place, you can usually avoid this copying by just
passing around pointers and everything shares access to that one object.
OTOH, when/if you need to copy the object anyway (e.g. if one copy will
be modified to become different from the other), this does little good.

As such, a tremendous amount depends upon things like: 1) what you're
allocating dynamically, 2) how you're using the dynamically allocated
objects, and 3) the degree to which objects you'd copy with manual
memory management can be shared in the presence of GC. All of these (and
more) depend on the application and design, not just the memory
management itself.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #3
On Jun 10, 11:30*am, Carlo Milanesi <carlo.milanesi.no.s...@libero.it>
wrote:
Hello,
* * *traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?
I almost always use smart pointers for objects. In any moderately
sized
system, the complexity of figuring out when to delete something is
just
not worth it. With smart pointers, you never have to delete.

Of course, memory managed *within* a class can be handled with raw
pointers.

So I don't see a real choie between using deletes and using smart
pointers
unless there is a special circumstance or platform.

We have yet to move or consider other forms of garbage collectors such
as that used in Java. Call me old fashioned ;).
Jun 27 '08 #4
On Jun 10, 9:42 am, Krice <pau...@mbnet.fiwrote:
On 10 kesä, 18:30, Carlo Milanesi <carlo.milanesi.no.s...@libero.it>
wrote:
But in which cases it is better to use one technique and in which cases
another?

It's probably a question that has no answer. But I like the
old school delete, because it's transparent, you know exactly
what it's doing and when.
I don't think so. Can you tell whether the delete here will be called:

void foo()
{
A * a = new A(/* ... */);
/* code that may throw today or some time in the future possibly
after some code change */
delete a;
}

To the OP: never deallocate resources explicitly in code. That would
not be "traditional," rather "developmental." :) I used to do that
when I didn't know better. :/

Ali
Jun 27 '08 #5
On Jun 10, 12:03 pm, "AnonMail2...@gmail.com" <AnonMail2...@gmail.com>
wrote:
On Jun 10, 11:30 am, Carlo Milanesi <carlo.milanesi.no.s...@libero.it>
wrote:
I almost always use smart pointers for objects. In any moderately
sized
system, the complexity of figuring out when to delete something is
just
not worth it.
The problem is, that complex code hoping to figure out when to
'delete' an object may never be executed. The non-throwing lines of
code of today can suddenly start possibly throwing in the future by
code changes, and the explicit delete statement may never be executed.
Of course, memory managed *within* a class can be handled with raw
pointers.
Unfortunately that statement must be qualified further: you are
talking about classes that manage a single object, right? Because the
following class fits your description, but is not exception-safe and
cannot manage the memory it hopes to manage:

class HopefulManager
{
One * one_;
Two * two_;

public:

HopefulManager()
:
one_(new One()),
two_(new Two()) // <- 1, <- 2
{
// some other code that may throw <- 3
}

~HopefulManager()
{
delete two_;
delete one_;
}
};

The three places that may cause resource leaks are:

1) new may throw, one_'s object is leaked

2) Two() may throw, one_'s object is leaked

3) Any line is the constructor may throw, one_'s and two_'s objects
are leaked
So I don't see a real choie between using deletes and using smart
pointers
unless there is a special circumstance or platform.
What I said above is regardless of special circumstances or platforms.
Pure C++... :)

Ali
Jun 27 '08 #6
In article <ga*******************************@ram.dialup.fu-berlin.de>,
ra*@zedat.fu-berlin.de says...
Jerry Coffin <jc*****@taeus.comwrites:
Allocating space to hold extra copies of the object, and copying
the relevant data into each copy, can take a considerable amount of
time. With a GC in place, you can usually avoid this copying by just
passing around pointers and everything shares access to that one object.
»There were two versions of it, one in Lisp and one in
C++. The display subsystem of the Lisp version was faster.
There were various reasons, but an important one was GC:
the C++ code copied a lot of buffers because they got
passed around in fairly complex ways, so it could be quite
difficult to know when one could be deallocated. To avoid
that problem, the C++ programmers just copied. The Lisp
was GCed, so the Lisp programmers never had to worry about
it; they just passed the buffers around, which reduced
both memory use and CPU cycles spent copying.«

<XN*****************@newssvr13.news.prodigy.com>
Intentionally or otherwise, I suspect your post is likely to generate
fare more heat than light. Most of it is unsupported assertions, and
none of it is from anybody who appears to deserve the title of "guru",
at least with respect to C++ (and IMO, probably not in any other respect
either).

The first quote appears to be purely apocryphal -- an unsupported
statement from somebody posting under a pseudonym, about software of
unknown origin written by people of unknown skills.

Joel Spolsky spends a lot of time writing about software, but his
credentials seem questionable at best. In particular, I've seen nothing
to give a really strong indication that he's much of a programmer
(himself) at all.

IBM, of course, has a great deal of collective knowledge about
programming -- but the bit you quote is written with the specific intent
of promoting Java. It's been discussed here before, and at very best
it's misleading when applied to more than the very specific domain about
which it's written.

Finally we get yet another reference to Ian Joyner's "Critique of C++."
IMO, there should be something similar to Godwin's law relating to
anybody who quotes (any part of) this. First of all, it has nothing to
do with the C++ of today, or anytime in the last decade or more. As of
the first edition, some (a small fraction) was reasonably accurate about
the C++ of the time -- but the updates in his second and third editions
were insufficient to keep the relevant to the C++ of their times, and
the third edition still predates the original C++ standard by a couple
of years. With respect to the C++ of today, it varies from irrelevant to
misleading to downright false. Second, a great deal of it was misleading
when it was originally written. Third, nearly all the rest of it was
downright false when written.

When you get down to it, despite being umpteen pages long, the
criticisms in this paper that have at least some degree of validity with
respect to current C++ can be summarized as:

1) member functions should be virtual by default.
2) C++ should have Concepts [JVC: C++ 0x will].
3) Unified syntax for "." and "->" would be nice.
4) "static" is overloaded in too many (confusing) ways.
5) Modules would be better than headers.
6) Support for DbC would have some good points.

When you get down to it, however, it would be much easier to summarize
his critique in a single sentence: "C++ isn't Eiffel." Many of his
individual arguments aren't really supported at all -- they're simply
statements that C++ must be wrong because it's different from Eiffel.

Don't get me wrong: my previous statement that GC is favored for some
situations under some circumstances still stands -- but IMO, none of
these quotes provides any real enlightenment. Quite the contrary, the
quote from IBM means _almost_ nothing, and the other three (between
them) mean far less still.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #7
On Jun 10, 5:37 pm, acehr...@gmail.com wrote:
The problem is, that complex code hoping to figure out when to
'delete' an object may never be executed. The non-throwing lines of
code of today can suddenly start possibly throwing in the future by
code changes, and the explicit delete statement may never be executed.
Is there any chance that C++0x will give us mandatory checking of
throw() clauses in function definitions? That would enable the
compiler to warn about leaks when exceptions might happen between
calls to new and delete.
--
franl
Jun 27 '08 #8
On Jun 11, 12:54 am, Jerry Coffin <jcof...@taeus.comwrote:
In article <garbage-collection-20080610202...@ram.dialup.fu-berlin.de>,
r...@zedat.fu-berlin.de says...
Jerry Coffin <jcof...@taeus.comwrites:
>Allocating space to hold extra copies of the object, and
>copying the relevant data into each copy, can take a
>considerable amount of time. With a GC in place, you can
>usually avoid this copying by just passing around pointers
>and everything shares access to that one object.
»There were two versions of it, one in Lisp and one in
C++. The display subsystem of the Lisp version was faster.
There were various reasons, but an important one was GC:
the C++ code copied a lot of buffers because they got
passed around in fairly complex ways, so it could be quite
difficult to know when one could be deallocated. To avoid
that problem, the C++ programmers just copied. The Lisp
was GCed, so the Lisp programmers never had to worry about
it; they just passed the buffers around, which reduced
both memory use and CPU cycles spent copying.«
<XNOkd.7720$zx1.5...@newssvr13.news.prodigy.com>
Intentionally or otherwise, I suspect your post is likely to
generate fare more heat than light. Most of it is unsupported
assertions, and none of it is from anybody who appears to
deserve the title of "guru", at least with respect to C++ (and
IMO, probably not in any other respect either).
You noticed that too.
The first quote appears to be purely apocryphal -- an
unsupported statement from somebody posting under a pseudonym,
about software of unknown origin written by people of unknown
skills.
The first quote is probably the one which does correspond most
to practical reality; I seem to recall a similar statement being
made by Walter Bright (who certainly does qualify as a C++
guru). But of course, it doesn't have to be that way.
Joel Spolsky spends a lot of time writing about software, but
his credentials seem questionable at best. In particular, I've
seen nothing to give a really strong indication that he's much
of a programmer (himself) at all.
Another case of "those who can, do; those who can't teach (or
write articles)".
IBM, of course, has a great deal of collective knowledge about
programming -- but the bit you quote is written with the
specific intent of promoting Java. It's been discussed here
before, and at very best it's misleading when applied to more
than the very specific domain about which it's written.
Finally we get yet another reference to Ian Joyner's "Critique
of C++." IMO, there should be something similar to Godwin's
law relating to anybody who quotes (any part of) this. First
of all, it has nothing to do with the C++ of today, or anytime
in the last decade or more. As of the first edition, some (a
small fraction) was reasonably accurate about the C++ of the
time -- but the updates in his second and third editions were
insufficient to keep the relevant to the C++ of their times,
and the third edition still predates the original C++ standard
by a couple of years. With respect to the C++ of today, it
varies from irrelevant to misleading to downright false.
Second, a great deal of it was misleading when it was
originally written. Third, nearly all the rest of it was
downright false when written.
When you get down to it, despite being umpteen pages long, the
criticisms in this paper that have at least some degree of
validity with respect to current C++ can be summarized as:
1) member functions should be virtual by default.
Which is just wrong, at least from a software engineering point
of view.
2) C++ should have Concepts [JVC: C++ 0x will].
3) Unified syntax for "." and "->" would be nice.
I don't think I agree with this one, either.
4) "static" is overloaded in too many (confusing) ways.
The price we pay for C compatibility.
5) Modules would be better than headers.
I don't think anyone could disagree with that one. Of course,
just about everyone has a different definition of what they mean
by "modules".
6) Support for DbC would have some good points.
Interestingly, I think that C++ today has the best support of
any language, although it's not automatic, and many programmers
fail to use it.
When you get down to it, however, it would be much easier to
summarize his critique in a single sentence: "C++ isn't
Eiffel." Many of his individual arguments aren't really
supported at all -- they're simply statements that C++ must be
wrong because it's different from Eiffel.
Don't get me wrong: my previous statement that GC is favored
for some situations under some circumstances still stands --
but IMO, none of these quotes provides any real enlightenment.
Quite the contrary, the quote from IBM means _almost_ nothing,
and the other three (between them) mean far less still.
I don't think that there is complete consensus among the gurus
as to when garbage collection would be appropriate. I would be
very suspicious, however, of anyone who claimed that it is
always appropriate, or never appropriate. That it's not
available in the standard toolkit is a definite flaw in the
language, but requiring it to be used in every case would
probably be even worse (but I don't think anyone has ever
proposted that).

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
Carlo Milanesi <ca********************@libero.itwrites:
Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which
cases another? IOW, which is the design criterion?
Reference counted smart pointers: never. They leak memory as soon as
you have bidirectionnal associations or cycles in your data
structures.

Garbage collectors: always. There are even real-time garbage
collectors, if you have real-time constraints.

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is
it advisable to change the memory management strategy of that working
system?
Well, usually garbage collectors give better performance.
http://www.jwz.org/doc/gc.html
But of course it depends on the application and datasets. It might be
easier to change the garbage collection strategy, selecting one more
adapted to the application, than to change the application to use
another memory management style. On the other hand, if you write your
code with reference counting, it is easy enough to disable reference
counting and fall back to garbage collection.

--
__Pascal Bourguignon__
Jun 27 '08 #10
Pascal J. Bourguignon wrote:
Carlo Milanesi <ca********************@libero.itwrites:
>Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which
cases another? IOW, which is the design criterion?

Reference counted smart pointers: never. They leak memory as soon as
you have bidirectionnal associations or cycles in your data
structures.
By that logic you mean he will always have bidirectional associations or
cycles in his data structures (thus NEVER use shared_ptr). In my years of
C++ I've had that very rare and when I did, I used weak_ptr to break the
cycle. How often do you have bidirectional associations in your data
structures? In thos projects that you have, which percent of the data
structures from the project has cycles?
Garbage collectors: always. There are even real-time garbage
collectors, if you have real-time constraints.
gc's are no silver bullet. They may be good in some scenarios but I don't
think they are good in any situation. Plus memory management is just a
small part of resource management in a C++ program (at least in my
programs).
Well, usually garbage collectors give better performance.
http://www.jwz.org/doc/gc.html
But of course it depends on the application and datasets.
Ah so then you contradict your previous "Garbage collectors: always".

--
Dizzy

Jun 27 '08 #11
dizzy <di***@roedu.netwrites:
Pascal J. Bourguignon wrote:
>Carlo Milanesi <ca********************@libero.itwrites:
>>But in which cases it is better to use one technique and in which
cases another? IOW, which is the design criterion?

Reference counted smart pointers: never. They leak memory as soon as
you have bidirectionnal associations or cycles in your data
structures.

By that logic you mean he will always have bidirectional associations or
cycles in his data structures (thus NEVER use shared_ptr). In my years of
C++ I've had that very rare and when I did, I used weak_ptr to break the
cycle. How often do you have bidirectional associations in your data
structures? In thos projects that you have, which percent of the data
structures from the project has cycles?
Often enough. But the main point is of course, if your language
doesn't allow you to express some ideas easily, then you won't try to
express those ideas. If having circular references in C++ is a PITA,
then we will try very hard to avoid them. (And thus, burning a lot of
wetware cycles that would be better allocated to resolving the true
problems, instead of these technicalities).

>Well, usually garbage collectors give better performance.
http://www.jwz.org/doc/gc.html
But of course it depends on the application and datasets.

Ah so then you contradict your previous "Garbage collectors: always".
Not really, in the following sentence you cut out, I explained that if
the currrent garbage collection algorithm wasn't good enough for your
application, it would be better to change this garbage collection
algorithm for another one more adapted to your particular
circumstances, rather than going back to manage memory manually.

--
__Pascal Bourguignon__
Jun 27 '08 #12
Fran wrote:
On Jun 10, 5:37 pm, acehr...@gmail.com wrote:
>The problem is, that complex code hoping to figure out when to
'delete' an object may never be executed. The non-throwing lines of
code of today can suddenly start possibly throwing in the future by
code changes, and the explicit delete statement may never be executed.

Is there any chance that C++0x will give us mandatory checking of
throw() clauses in function definitions? That would enable the
compiler to warn about leaks when exceptions might happen between
calls to new and delete.
Why is there such a need? Always assume anything may throw and code
accordingly. In the exceptional cases where writing exception safe code is
not possible (making the code expensive or error prone) I'm sure you can
find a solution (like std::stack has for top()/pop()).

--
Dizzy

Jun 27 '08 #13
On 11 kesä, 00:25, acehr...@gmail.com wrote:
void foo()
{
A * a = new A(/* ... */);
/* code that may throw today or some time in the future possibly
after some code change */
delete a;

}
Throw what? A ball?
Jun 27 '08 #14
In article <bcb28001-8bed-4732-8191-b97f61e511b3
@k13g2000hse.googlegroups.com>, ja*********@gmail.com says...

[ ... ]
The first quote appears to be purely apocryphal -- an
unsupported statement from somebody posting under a pseudonym,
about software of unknown origin written by people of unknown
skills.

The first quote is probably the one which does correspond most
to practical reality; I seem to recall a similar statement being
made by Walter Bright (who certainly does qualify as a C++
guru). But of course, it doesn't have to be that way.
Right -- my point wasn't that the quote was wrong, only that it didn't
really add much. If somebody disagreed with (essentially) the same point
when I said it probably wouldn't find much in this to convince them (of
anything).
Joel Spolsky spends a lot of time writing about software, but
his credentials seem questionable at best. In particular, I've
seen nothing to give a really strong indication that he's much
of a programmer (himself) at all.

Another case of "those who can, do; those who can't teach (or
write articles)".
....except that most of the people I can think of who write specifically
about C++ really _can_ write code, and most of them clearly _do_, and as
a rule do it quite well at that. The only prominent exception would be
Scott Meyers, who's pretty open about the fact that he consults about
C++, teaches C++, but does NOT really write much C++ at all. OTOH, I'm
pretty sure that if he really needed (or wanted to) he could write code
quite nicely as well -- though given his talents as a teacher, I think
it would be rather a waste if he spent his time that way.

Others, however (e.g. David Abrahams, Andrei Alexandrescu, Andrew
Koenig, Herb Sutter) who write about C++, also appear to write a fair
amount of code, and mostly do it quite well at that (and no, I'm not
claiming to be such a guru that I'm in a position to rate the experts,
or anything like that...)

[ ... ]
When you get down to it, despite being umpteen pages long, the
criticisms in this paper that have at least some degree of
validity with respect to current C++ can be summarized as:
1) member functions should be virtual by default.

Which is just wrong, at least from a software engineering point
of view.
Right -- I don't mean to imply that all these are correct, or anything
like that -- I just mean that:

1) they're clearly enough defined to be fairly sure what he's saying.
2) they aren't obviously obsolete.
3) They aren't simply of the form: "Eiffel does it differently."

They're points that can be discussed intelligently, their strengths and
weaknesses can be examined, etc. They're not necessarily right, but at
least you can define (to at least some degree) what it means for them to
be right or wrong.

[ ... ]
I don't think that there is complete consensus among the gurus
as to when garbage collection would be appropriate. I would be
very suspicious, however, of anyone who claimed that it is
always appropriate, or never appropriate. That it's not
available in the standard toolkit is a definite flaw in the
language, but requiring it to be used in every case would
probably be even worse (but I don't think anyone has ever
proposted that).
I'm not sure it really needs to be part of the standard library, but I
do think it would be a good thing to tighten up the language
specification to the point that almost any known type of GC could be
included without leading to undefined behavior -- but we've been over
that before...

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #15
Jerry Coffin <jc*****@taeus.comwrites:
I'm not sure it really needs to be part of the standard library, but I
do think it would be a good thing to tighten up the language
specification to the point that almost any known type of GC could be
included without leading to undefined behavior
Well said!
-- but we've been over
that before...
Ok.

--
__Pascal Bourguignon__
Jun 27 '08 #16
On Jun 11, 6:56 am, Krice <pau...@mbnet.fiwrote:
On 11 kesä, 00:25, acehr...@gmail.com wrote:
void foo()
{
A * a = new A(/* ... */);
/* code that may throw today or some time in the future possibly
after some code change */
delete a;
}

Throw what? A ball?
No, an exception; unless you are imagining a type named "ball" of
course. :p

I can't believe you are serious; you must have forgotten the smiley...
Seriously though, if you really didn't know what I meant with "throw,"
you should learn about exceptions.

Ali
Jun 27 '08 #17
On 11 kesä, 19:43, acehr...@gmail.com wrote:
Seriously though, if you really didn't know what I meant with "throw,"
you should learn about exceptions.
Exceptions are not logical. If construction of the object
fails then what? The program fails also, usually. I never
check anything, not since they invented exceptions, so
I'm assuming that there are no exceptions:)

Jun 27 '08 #18
In article <d9177235-e278-46e6-a709-cdac9bb80a53
@b1g2000hsg.googlegroups.com>, pa****@mbnet.fi says...
On 11 kesä, 19:43, acehr...@gmail.com wrote:
Seriously though, if you really didn't know what I meant with "throw,"
you should learn about exceptions.
Exceptions are not logical. If construction of the object
fails then what? The program fails also, usually. I never
check anything, not since they invented exceptions, so
I'm assuming that there are no exceptions:)
Oh my. In most cases you can do something reasonably productive when an
exception gets thrown. Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can, which
is typically quite a bit more than the runtime library is likely to do
on its own.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #19
Stefan Ram wrote:
Jerry Coffin <jc*****@taeus.comwrites:
>>Oh my. In most cases you can do something reasonably productive when an
exception gets thrown. Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can

A function should not be coupled to an application more than
necessary, so that the function might be used in a library as well
(or one might even write functions for use in a library).

Usually, a function does not know which user interface the
program calling it employs. »::std::cout« might be associated
with a console, or it might not be, when the application is GUI
based, web based or a driver or a service without a user interface.

So what should »print out« mean in the general case?
Should the function use »::std::cout << ...« or what else to
»print out« the most meaningful error message it can?
Of course, printing a message for the user is the last resort. We must
assume that all better ways of responding in a more specific way are
blocked (for whatever reason). In that case, at a point where you cannot
determine what "print out" means, you still have the option of letting the
exception propagate higher in the call stack. At some point, it has to be
known what "print out" means.
Best

Kai-Uwe Bux
Jun 27 '08 #20
In article <MP************************@news.sunsite.dk>,
jc*****@taeus.com says...

[ ... ]
That's the whole point of using an exception: delaying handling of the
error until you reach a point at which it's apparent how it should be
handled.
Pardon me -- it's not really the _whole_ point, but merely part of the
point. Nonetheless, it's an important part of the point...

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #21
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
Oh my. In most cases you can do something reasonably productive when an
exception gets thrown.
Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can
"Error: object can't be constructed."
Jun 27 '08 #22
Carlo Milanesi wrote:
Hello,
traditionally, in C++, dynamically allocated memory has been managed
explicitly by calling "delete" in the application code.

Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.

But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?
For scarce resources, like resource handles and large memory blocks, use
reference counting. For routine memory allocations, use gc.

And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?
Using gc effectively entails using different coding/design techniques,
so it is not practical to try to shift the design after the fact.

-------------
Walter Bright
Digital Mars
http://www.digitalmars.com
C, C++, D programming language compilers
Jun 27 '08 #23
Krice wrote:
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
>Oh my. In most cases you can do something reasonably productive
when an exception gets thrown.

Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
The task being performed might fail, but not the whole server.
>
>Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can

"Error: object can't be constructed."
"Query result too large - please use a more specific selection"
Bo Persson
Jun 27 '08 #24
Jerry Coffin wrote:
[ ... ]
Very interesting. Are there nice readings in the inet about this topic,
which include some C++ snippets for everday usage?
-- Maik
Jun 27 '08 #25
"Krice" <pa****@mbnet.fiwrote in message
news:4f**********************************@z72g2000 hsb.googlegroups.com...
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
Oh my. In most cases you can do something reasonably productive when an
exception gets thrown.
Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
Not always true. Lets say that the object requested a synchronization
resource from the OS, but failed because too many of them were in use my the
program. Well, the exception handler could run some "purge" procedures to
try an rid itself of cached unnecessary state, ect... and defer trying again
to a later time. On a server, if an object fails construction during the
initialization process of a new connection, the exception handler could send
a message to the client application saying something like "Server overload;
try again later.". I could go on and on. The main point is that an
application can attempt to mutate the conditions which caused the exception
and defer trying again until things settle down. Sometimes, you can recover
from exceptions quite nicely.

One example in C... If malloc returns NULL, what do you do? Well, you could
try something like:

http://groups.google.com/group/comp....7956d31e6ca5cc

;^)

Jun 27 '08 #26
On Jun 11, 1:50*pm, "Bo Persson" <b...@gmb.dkwrote:
Krice wrote:
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
Oh my. In most cases you can do something reasonably productive
when an exception gets thrown.
Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.

The task being performed might fail, but not the whole server.
Yes, I think this sort of situation should be considered:

AccountBase
|
Account1_1
|
Account1_2

If the program is expecting to receive an Account1_2 object
over a network and a read fails/times out, I want to have the
object preserved as an Account1_1 if that much of the object
was successfully received. In baseball sometimes a hit is more
than a single, but not a double. If a runner tries to turn it
into a double he's thrown out. A double is better than a
single, but a single is much better than an out.

Brian Wood
Ebenezer Enterprises
www.webEbenezer.net
Jun 27 '08 #27
In article <ex*******************************@ram.dialup.fu-berlin.de>,
ra*@zedat.fu-berlin.de says...

[ ... ]
Ada83, and possibly already Algol68 and Clu had exceptions,
but I do not know who first came up with this concept.
Maybe it is inspired from processors, which might raise
interrupts, error signals or traps to invoke handlers.
PL/I had them in 1964. BASIC has had some exception handling-like stuff
(e.g. on error goto) for quite a while as well, though I'm not sure
whether it was in the original 1964 version or not.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #28
In article <4f6f494b-3511-4d36-89ac-2f0d32f49877
@z72g2000hsb.googlegroups.com>, pa****@mbnet.fi says...
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
Oh my. In most cases you can do something reasonably productive when an
exception gets thrown.
Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
Maybe it can and maybe it can't. It depends entirely on what kind of
object you're trying to create and how important it is to the program.
In some cases it truly is crucial to the program, and all you can do is
print out the error message and quit. In other cases, it may be purely
cosmetic, and the program can do its real work without it. In still
other cases, there may be _other_ things that are more or less cosmetic
that can be discarded when/if necessary to allow the real work to
finish.

Just for example, I've written quite a few programs that have some sort
of windowed interface. Many of them display some sort of bitmap in the
background -- but if the system runs low of memory, they can discard the
bitmap, and get along with a plain grey background for a while.
Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can
"Error: object can't be constructed."
Usually you can come up with something more meaningful than that -- at
the very least, something about the type of object whose construction
failed, and the operation(s) being attempted when the failure happened.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #29
On Jun 11, 9:37 pm, Krice <pau...@mbnet.fiwrote:
On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
Oh my. In most cases you can do something reasonably
productive when an exception gets thrown.
Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
It depends why the object can't be constructed. There are a lot
of things one can recover from.
Even in the worst case, you probably want to catch it and
print out the most meaningful error message you can
"Error: object can't be constructed."
Respond to the request with an "insufficient resources" error
(in case of bad_alloc, for example)?

Like most things, exceptions have a cost---in particular, they
do disrupt program logic. There are some specific cases,
however (not many, really, but although few, they occur fairly
frequently) in which the cost of the alternatives is higher. If
you run out of memory processing a request in a server, you
can't just bring the server down; you have to respond with an
"insufficient resources" error (and continue to accept simpler
requests). And there's no way to check before constructing an
object that it will have sufficient memory, so you have no
choice but to detect the error in the constructor.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #30
On Jun 11, 4:20 pm, Jerry Coffin <jcof...@taeus.comwrote:
In article <bcb28001-8bed-4732-8191-b97f61e511b3
@k13g2000hse.googlegroups.com>, james.ka...@gmail.com says...
[ ... ]
Joel Spolsky spends a lot of time writing about software, but
his credentials seem questionable at best. In particular, I've
seen nothing to give a really strong indication that he's much
of a programmer (himself) at all.
Another case of "those who can, do; those who can't teach (or
write articles)".
...except that most of the people I can think of who write
specifically about C++ really _can_ write code, and most of
them clearly _do_, and as a rule do it quite well at that.
That was probably true at the beginning, but now adays, just
about everybody thinks they have to write about C++, and most of
what I see is junk. (Joel Spolsky is probably better than
average, in fact, although I wouldn't consider him an authority
in any of the fields he writes about.)
The only prominent exception would be Scott Meyers, who's
pretty open about the fact that he consults about C++, teaches
C++, but does NOT really write much C++ at all. OTOH, I'm
pretty sure that if he really needed (or wanted to) he could
write code quite nicely as well -- though given his talents as
a teacher, I think it would be rather a waste if he spent his
time that way.
Scott is actually one of the few who really knows what he is
talking about. Go down to your local bookstore, randomly pick
up any number of books about C++, and see how many are written
by someone who has any idea what they are really talking about.
Others, however (e.g. David Abrahams, Andrei Alexandrescu,
Andrew Koenig, Herb Sutter) who write about C++, also appear
to write a fair amount of code, and mostly do it quite well at
that (and no, I'm not claiming to be such a guru that I'm in a
position to rate the experts, or anything like that...)
There are certainly some exceptions, and we (you and I) know
them. On the other hand, they are how many, compared to all of
the authors of "C++ for NULL's", "C++ in 7 Days", or whatever.
Take a look at the various web sites proposing C++ information:
how many of them are useful, or even correct? For every Sutter,
it seems like there are dozens of Schildts.
[ ... ]
I don't think that there is complete consensus among the gurus
as to when garbage collection would be appropriate. I would be
very suspicious, however, of anyone who claimed that it is
always appropriate, or never appropriate. That it's not
available in the standard toolkit is a definite flaw in the
language, but requiring it to be used in every case would
probably be even worse (but I don't think anyone has ever
proposted that).
I'm not sure it really needs to be part of the standard
library, but I do think it would be a good thing to tighten up
the language specification to the point that almost any known
type of GC could be included without leading to undefined
behavior -- but we've been over that before...
I was about to say... The reason why it needs to be standard is
because it's not just a library issue.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #31
On Jun 11, 1:21 pm, dizzy <di...@roedu.netwrote:
Pascal J. Bourguignon wrote:
Carlo Milanesi <carlo.milanesi.no.s...@libero.itwrites:
Hello,
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application code.
Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.
But in which cases it is better to use one technique and in which
cases another? IOW, which is the design criterion?
Reference counted smart pointers: never. They leak memory
as soon as you have bidirectionnal associations or cycles in
your data structures.
By that logic you mean he will always have bidirectional
associations or cycles in his data structures (thus NEVER use
shared_ptr). In my years of C++ I've had that very rare and
when I did, I used weak_ptr to break the cycle. How often do
you have bidirectional associations in your data structures?
In thos projects that you have, which percent of the data
structures from the project has cycles?
Hmmm. I don't think I've ever had an application where there
were no cycles. Cycles are everywhere, starting with double
linked lists. Navigation between objects is rarely
unidirectional.

Whether this is relevant to the argument at hand is a different
question. Nobody but a fool would recommend just replacing all
raw pointers with boost::shared_ptr. On the other hand, there
are small subsets of the overall problem where it is the
appropriate solution---sometimes even when you're using garbage
collection for the general case.

The power of C++ is that it offers such alternatives.
Garbage collectors: always. There are even real-time garbage
collectors, if you have real-time constraints.
gc's are no silver bullet. They may be good in some scenarios
but I don't think they are good in any situation.
(I suspect that you meant every, not any.)
Plus memory management is just a small part of resource
management in a C++ program (at least in my programs).
Memory tends to be somewhat different from other resources
because its use is so ubiquious, and also because there's so
much of it, and release doesn't normally have any other side
effects. Also, memory is where "objects" reside, and as such,
is involved in issues such as type safety.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #32
On Jun 11, 9:38 pm, Walter Bright <wal...@digitalmars-nospamm.com>
wrote:
Carlo Milanesi wrote:
traditionally, in C++, dynamically allocated memory has been
managed explicitly by calling "delete" in the application
code.
Now, in addition to the standard library strings,
containers, and auto_ptrs, gurus suggest that may be better
to use a reference-counted smart pointer, or a
garbage-collector.
But in which cases it is better to use one technique and in
which cases another? IOW, which is the design criterion?
For scarce resources, like resource handles and large memory
blocks, use reference counting. For routine memory
allocations, use gc.
That's one of the best summaries I've heard. I would add two
things, however:

-- For objects with value semantics, don't use dynamic
allocation at all. (I know you're aware of the tradeoffs,
but lately, we've seen a lot of people coming from Java who
allocate everything dynamically---even things like Complex.)

-- Neither garbage collection nor (usually) reference counting
deterministically define object lifetime. Objects whose end
of lifetime must have visible side effects (and that's most
of the dynamically allocated objects in some types of
application) still need code to manage this.
And if, after having completed a working system, a technique
would result more performing than another, or better for
other reasons, is it advisable to change the memory
management strategy of that working system?
Using gc effectively entails using different coding/design
techniques, so it is not practical to try to shift the design
after the fact.
Yes and no. Simply replacing the global operator new and
operator delete to use garbage collection will result in more
reliable code, even if the application was originally written
without garbage collection in mind.

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #33
In article <4f**********************************@z72g2000hsb. googlegroups.com>,
Krice <pa****@mbnet.fiwrote:
>On 11 kesä, 20:33, Jerry Coffin <jcof...@taeus.comwrote:
>Oh my. In most cases you can do something reasonably productive when an
exception gets thrown.

Like what? If the object can't be constructed then there is
something seriously wrong and the program can't obviously
recover from that.
Depend on the program. Think about an operating system or a server.
>Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can

"Error: object can't be constructed."
Example of error message returned to user:

On my mobile, if I try to browse the web with heavily graphical
pages, especially if I open more than one window, I regularly get a
message: "Memory full, please close some other applications". Do you
think this is a bad idea and that it would be better for the mobile to
shutdown and turn itself off? Or even the lesser evil of having the
webbrowser application exit hence killing either my other open window
and my previous page history? I certainly don't think so. The mobile
shuting down would make me throw it one the wall. Even loosing my
other windows and history would seriously annoy me. Instead, this
message allow me to either close my second window or go back in my
history to where I came from and continue what I was doing
previously.

Example of recovery:

A server parses data it receives from the network. It's architecture
is multithreaded, receiver threads receive data and store them on disk
temporarily. processing threads read data from the disk, parse and
potentially modify it and write it back on disk, sender thread forward
the processed data elsewhere. There are many threads of each types
and queues to communicate between the three stage of processing. For
some reason, processing require a lot of memory, let say 10 times the
size of the data. The average data size is small (say 20K) but
occasionally, some data might go up to 100Mb in size. There's 10
processing threads. Circumstance may happen that there are 10
consecutive 100Mb jobs on the processing queue and all 10 processing
threads get to start one large job at the same time. At some point one
of the processing thread might attempt to create a large data
containing object and fail because of lack of resources. It would
then be a sensible option for an exception to be thrown up and allowed
to propagate up the stack until say the queue reader receives it. A
possible recovery mechanism would be to requeue this large job at the
back of the queue. By the time it come back, the system has good
chances not to be as busy with 10 large requests hence be able to
process that job.
Yannick


Jun 27 '08 #34
In article <ef2c8374-5a6e-4a5c-a040-
ce**********@k13g2000hse.googlegroups.com>, ja*********@gmail.com
says...

[ ... ]
That was probably true at the beginning, but now adays, just
about everybody thinks they have to write about C++, and most of
what I see is junk. (Joel Spolsky is probably better than
average, in fact, although I wouldn't consider him an authority
in any of the fields he writes about.)
Quite true -- there are definitely worse around the Spolsky.

[ ... ]
Others, however (e.g. David Abrahams, Andrei Alexandrescu,
Andrew Koenig, Herb Sutter) who write about C++, also appear
to write a fair amount of code, and mostly do it quite well at
that (and no, I'm not claiming to be such a guru that I'm in a
position to rate the experts, or anything like that...)

There are certainly some exceptions, and we (you and I) know
them. On the other hand, they are how many, compared to all of
the authors of "C++ for NULL's", "C++ in 7 Days", or whatever.
Take a look at the various web sites proposing C++ information:
how many of them are useful, or even correct? For every Sutter,
it seems like there are dozens of Schildts.
Unfortunately, all too true. The one good point is that since C++ has
"gone out of fashion", many (perhaps most) of the worst have moved on
and are turning out dreck about Ruby on Rails, or whatever this week's
fad happens to be...

[ ... ]
I'm not sure it really needs to be part of the standard
library, but I do think it would be a good thing to tighten up
the language specification to the point that almost any known
type of GC could be included without leading to undefined
behavior -- but we've been over that before...

I was about to say... The reason why it needs to be standard is
because it's not just a library issue.
I still think the standard should be written to _allow_ almost any sort
of GC (including copying collectors) but not to require any sort.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #35
Maik Beckmann wrote:
Jerry Coffin wrote:
>[ ... ]

Very interesting. Are there nice readings in the inet about this topic,
which include some C++ snippets for everday usage?

Found this
http://www.ddj.com/cpp/184401632

If you know more links please post them.
Jun 27 '08 #36
In article <MP************************@news.sunsite.dk>,
Jerry Coffin <jc*****@taeus.comwrote:
>In article <ef2c8374-5a6e-4a5c-a040-
ce**********@k13g2000hse.googlegroups.com>, ja*********@gmail.com
says...

[ ... ]
>That was probably true at the beginning, but now adays, just
about everybody thinks they have to write about C++, and most of
what I see is junk. (Joel Spolsky is probably better than
average, in fact, although I wouldn't consider him an authority
in any of the fields he writes about.)

Quite true -- there are definitely worse around the Spolsky.
I think an important distinction is that Spolsky never claimed to
write about C++. He writes about software development from a CTO /
CEO / Development manager perspective and touch a lot of subject.
However, he generalises and doesn't really go into the low level
details. That's fine for what he writes about. A CTO shouldn't
micro-manage and must generalise even if generalisation are sometimes
wrong. It's the job of the technical specialist to correct the CTO
when details are wrong :-)

OTOH Meyer / Alexandrescu / Sutter write specifically about C++ and go
into details and must get the details right. As long as one doesn't
try to define good class design from Spolsky's writings or use "Modern
C++ Design" for fresh graduate interview questions, there shouldn't be
too much problems.

IMO, what causes more damage are the "Learn C++ in 24 hours for null
dummmies" type of books or even worse, ex-C programmers that have been
promoted to management, have never bothered updating their skill sets
and are now promoting / recommending / imposing 20 years out of date
techniques from a totally different language to junior programmers.

Yannick
Jun 27 '08 #37
On Jun 12, 4:44 pm, ytrem...@nyx.nyx.net (Yannick Tremblay) wrote:
In article <MPG.22badae6598ac516989...@news.sunsite.dk>,
Jerry Coffin <jcof...@taeus.comwrote:
In article <ef2c8374-5a6e-4a5c-a040-
cee133409...@k13g2000hse.googlegroups.com>, james.ka...@gmail.com
says...
[ ... ]
That was probably true at the beginning, but now adays, just
about everybody thinks they have to write about C++, and most of
what I see is junk. (Joel Spolsky is probably better than
average, in fact, although I wouldn't consider him an authority
in any of the fields he writes about.)
Quite true -- there are definitely worse around the Spolsky.
I think an important distinction is that Spolsky never claimed to
write about C++. He writes about software development from a CTO /
CEO / Development manager perspective and touch a lot of subject.
However, he generalises and doesn't really go into the low level
details. That's fine for what he writes about. A CTO shouldn't
micro-manage and must generalise even if generalisation are sometimes
wrong. It's the job of the technical specialist to correct the CTO
when details are wrong :-)
Certainly. He writes about software engineering. But even
there, I wouldn't consider him a reference. He's obviously more
competent than most, but his presentations are more annecdotal
than anything else.
OTOH Meyer / Alexandrescu / Sutter write specifically about C++ and go
into details and must get the details right. As long as one doesn't
try to define good class design from Spolsky's writings or use "Modern
C++ Design" for fresh graduate interview questions, there shouldn't be
too much problems.
IMO, what causes more damage are the "Learn C++ in 24 hours for null
dummmies" type of books or even worse, ex-C programmers that have been
promoted to management, have never bothered updating their skill sets
and are now promoting / recommending / imposing 20 years out of date
techniques from a totally different language to junior programmers.
That's sometimes a problem: a lot of university courses here got
upgraded from C to C++ without the prof bothering to learn the
new language, at least not any more than using new/delete
instead of malloc/free. The result is a large number of
beginners who really don't know C++, even though they've learned
it at school. In practice, however, I don't find that too great
a problem: there are so many things you don't learn in school,
and if the person is in any way competent, with a good mentor,
he'll catch on quickly. If I look at the experienced C++
programmer (the ones who will serve as mentors), I see a lot of
extremes---either C++ as they learned it, twenty years ago, or
the most complicated TMP from Alexandrescu's book to solve the
simplest, one of problem. (In my experience, the latter seem to
outnumber the former by better than two to one.)

--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #38
Yannick Tremblay kirjoitti:
message: "Memory full, please close some other applications". Do you
think this is a bad idea and that it would be better for the mobile to
shutdown and turn itself off?
All these examples where memory recovery is needed seem to be
anything else than normal application running in PC, so I guess
it's good to have exceptions when they have some kind of real
function, but I think it's a waste of time to write such code in
PC application, because the construction never(?) fails, unless
you run out of memory.
Jun 27 '08 #39
Krice ha scritto:
Yannick Tremblay kirjoitti:
>message: "Memory full, please close some other applications". Do you
think this is a bad idea and that it would be better for the mobile to
shutdown and turn itself off?

All these examples where memory recovery is needed seem to be
anything else than normal application running in PC, so I guess
it's good to have exceptions when they have some kind of real
function, but I think it's a waste of time to write such code in
PC application, because the construction never(?) fails, unless
you run out of memory.
What do you mean with "some kind of real function"?

Even in PC applications exceptions are very useful.
Try to create a 99999x99999 color bitmap using Windows Paint
(mspaint.exe) and you will get an error message, but the application
will continue to run. Would you prefer a crash?

--
Carlo Milanesi
http://digilander.libero.it/carlmila
Jun 27 '08 #40
pj*@informatimago.com (Pascal J. Bourguignon) kirjutas:
Reference counted smart pointers: never. They leak memory as soon as
you have bidirectionnal associations or cycles in your data
structures.
A point in favor of reference-counted smartpointers: sometimes it is good
to know if there are other references to an object, for example for
supporting copy-on-write technics or avoiding a deep copy when passing an
object over to another thread. I think this info is hard to obtain from a
GC implementation (would probably require a mark cycle to be run). In case
of reference counting the information is naturally there.

As for cycles, I have come to conclusion that the need to avoid cycles in
smartpointer chains actually forces one to think out and clean up the
design and simplifies the overall structure of the software. Of course,
this depends on the application domain, I can well imagine that sometimes
cycles are inevitable (and then there are weak smartpointers for resolving
this, right? I have not yet have had a need for them (apart imagined needs,
I mean;-)).

Regards
Paavo
Jun 27 '08 #41
In article <e1dc93ef-99f4-4754-ae48-
ae**********@e53g2000hsa.googlegroups.com>, pa****@mbnet.fi says...
Yannick Tremblay kirjoitti:
message: "Memory full, please close some other applications". Do you
think this is a bad idea and that it would be better for the mobile to
shutdown and turn itself off?

All these examples where memory recovery is needed seem to be
anything else than normal application running in PC, so I guess
it's good to have exceptions when they have some kind of real
function, but I think it's a waste of time to write such code in
PC application, because the construction never(?) fails, unless
you run out of memory.
Construction can fail for _lots_ of reasons other than running out of
memory. In networking, for example, you might have an object to
represent a connection to a server. If you can't connect to the server,
you can't create the connection object. OTOH, that hardly implies that
the program must fail -- you might easily have a number of servers to
try, and as long as you can connect to any one of them, your program can
continue to run perfectly well.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #42
In message <pr******************@ram.dialup.fu-berlin.de>, Stefan Ram
<ra*@zedat.fu-berlin.dewrites
>Jerry Coffin <jc*****@taeus.comwrites:
>>Oh my. In most cases you can do something reasonably productive when an
exception gets thrown. Even in the worst case, you probably want to
catch it and print out the most meaningful error message you can

A function should not be coupled to an application more than
necessary, so that the function might be used in a library as well
(or one might even write functions for use in a library).

Usually, a function does not know which user interface the
program calling it employs. ›::std::cout‹ might be associated
with a console, or it might not be, when the application is GUI
based, web based or a driver or a service without a user interface.

So what should ›print out‹ mean in the general case?
Should the function use ›::std::cout << ...‹ or what else to
›print out‹ the most meaningful error message it can?
It should delegate that decision to your chosen logging package.

--
Richard Herring
Jun 27 '08 #43
Carlo Milanesi wrote:
Even in PC applications exceptions are very useful.
Try to create a 99999x99999 color bitmap using Windows Paint
(mspaint.exe) and you will get an error message, but the application
will continue to run. Would you prefer a crash?
Guarding against invalid user input is not a good use case for
exceptions. Erroneous user input is hardly exceptional, is it?

Jun 27 '08 #44
Matthias Buelow wrote:
Carlo Milanesi wrote:
>Even in PC applications exceptions are very useful.
Try to create a 99999x99999 color bitmap using Windows Paint
(mspaint.exe) and you will get an error message, but the application
will continue to run. Would you prefer a crash?

Guarding against invalid user input is not a good use case for
exceptions. Erroneous user input is hardly exceptional, is it?
Depends on the situation really. The input that the user has entered in
this case is actually valid, in that it is a real size, but the error is
more likely caused by inability to allocate the necessary memory for
such a huge bitmap.

I'd call that exceptional even if it is ultimately caused by a stupid user.
Jun 27 '08 #45
Matthias Buelow ha scritto:
Carlo Milanesi wrote:
>Even in PC applications exceptions are very useful.
Try to create a 99999x99999 color bitmap using Windows Paint
(mspaint.exe) and you will get an error message, but the application
will continue to run. Would you prefer a crash?

Guarding against invalid user input is not a good use case for
exceptions. Erroneous user input is hardly exceptional, is it?
It not an invalid input. In this program you can specify a width from 1
to 99999 pixels and a height from 1 to 99999 pixels.
For example, I can create a 10x99999 bitmap or a 99999x10 bitmap.
This program appears to allocate about 6 to 10 bytes for every pixel.
Perhaps, if your computer can allocate 60 GB of virtual memory for a
single process you can create such a bitmap.
It would be silly to limit the memory of the bitmap, as different users
may have different memory.
I think that raising an exception is the best way to handle this kind
user input.

--
Carlo Milanesi
http://digilander.libero.it/carlmila
Jun 27 '08 #46
On Jun 12, 12:38*am, Walter Bright <wal...@digitalmars-nospamm.com>
wrote:
Carlo Milanesi wrote:
Hello,
* * traditionally, in C++, dynamically allocated memory has been managed
explicitly by calling "delete" in the application code.
Now, in addition to the standard library strings, containers, and
auto_ptrs, gurus suggest that may be better to use a reference-counted
smart pointer, or a garbage-collector.
But in which cases it is better to use one technique and in which cases
another? IOW, which is the design criterion?

For scarce resources, like resource handles and large memory blocks, use
reference counting. For routine memory allocations, use gc.
And if, after having completed a working system, a technique would
result more performing than another, or better for other reasons, is it
advisable to change the memory management strategy of that working system?

Using gc effectively entails using different coding/design techniques,
so it is not practical to try to shift the design after the fact.

-------------
Walter Bright
Digital Marshttp://www.digitalmars.com
C, C++, D programming language compilers
What is the work of Garbage collector?
Jun 27 '08 #47

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

Similar topics

1
by: Bob | last post by:
Are there any known applications out there used to test the performance of the .NET garbage collector over a long period of time? Basically I need an application that creates objects, uses them, and...
4
by: Pedro Miguel Carvalho | last post by:
Greetings. I'm creating a project that as a intricate relation between object kind of like a set where each object in the set can be connect to a subset of object of the set and objects not in...
10
by: pachanga | last post by:
The Hans-Boehm garbage collector can be successfully used with C and C++, but not yet a standard for C++.. Is there talks about Garbage Collector to become in the C++ standard?
6
by: Ana | last post by:
Hi! I have problems with the following scenario: My application is developed using C# under .NET. It must run on all Windows versions starting from Windows 98. The user must open different...
4
by: R. MacDonald | last post by:
Hello, all, I have a .NET application (VB) that passes the address of a delegate to unmanaged code in a DLL. The unmanaged code then uses the delegate as a call-back. This seems to work...
13
by: Mingnan G. | last post by:
Hello everyone. I have written a garbage collector for standard C++ application. It has following main features. 1) Deterministic Finalization Providing deterministic finalization, the system...
44
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable...
350
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use...
0
by: raylopez99 | last post by:
I ran afoul of this Compiler error CS1612 recently, when trying to modify a Point, which I had made have a property. It's pointless to do this (initially it will compile, but you'll run into...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
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...
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...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.