473,508 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Garbage collection in C++

Hi all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

Regards,
Pushpa
Nov 15 '08 #1
158 7690
<pu**********@gmail.comwrote in message
news:22**********************************@a29g2000 pra.googlegroups.com...
Hi all,

Is garbage collection possible in C++.
Sure:

http://www.hpl.hp.com/personal/Hans_Boehm/gc

It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.
C++ is a low-level systems language, IMVHO, that's no place for a GC to
be...

Nov 15 '08 #2
On Nov 15, 10:32*am, "Chris M. Thomasson" <n...@spam.invalidwrote:
<pushpakul...@gmail.comwrote in message

news:22**********************************@a29g2000 pra.googlegroups.com...
Hi all,
Is garbage collection possible in C++.

Sure:

http://www.hpl.hp.com/personal/Hans_Boehm/gc
It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

C++ is a low-level systems language, IMVHO, that's no place for a GC to
be...
Check out: http://www.research.att.com/~bs/bs_f...age-collection

- bharath
Nov 15 '08 #3
pu**********@gmail.com wrote:
Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.
I have absolutely no experience in third-party garbage collectors for
C++. What I have always wondered, though, is how those can handle a
situation like:

int* foo()
{
int* table = new int[100];
return table+40;
}

The pointer to the beginning of the allocated array dies when foo()
terminates, but a pointer to one of its elements lives beyond the scope
of foo(). This pointer may be used in the calling code. A garbage
collector would have to:

1) Know that there's still a live pointer pointing to (an element
inside) the array, and thus it cannot destroy it yet.

2) Know to delete the array properly (ie. from the original pointer
pointing to the beginning of the array, rather than the one which lived
longer than that) when that returned pointer dies and the GC runs.

I suppose they have figured out these problems. I'm just wondering how.
Nov 15 '08 #4
On 2008-11-15 12:21:06 -0500, Juha Nieminen <no****@thanks.invalidsaid:
>
I have absolutely no experience in third-party garbage collectors for
C++. What I have always wondered, though, is how those can handle a
situation like:

int* foo()
{
int* table = new int[100];
return table+40;
}

The pointer to the beginning of the allocated array dies when foo()
terminates, but a pointer to one of its elements lives beyond the scope
of foo(). This pointer may be used in the calling code. A garbage
collector would have to:

1) Know that there's still a live pointer pointing to (an element
inside) the array, and thus it cannot destroy it yet.

2) Know to delete the array properly (ie. from the original pointer
pointing to the beginning of the array, rather than the one which lived
longer than that) when that returned pointer dies and the GC runs.

I suppose they have figured out these problems. I'm just wondering how.
It's just a bit of bookkeeping. When the array is allocated the
collector makes notes about the size of the allocated block and where
it begins. The returned pointer points into the allocated block, so the
block is still live.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Nov 15 '08 #5

<pu**********@gmail.comwrote in message
news:22**********************************@a29g2000 pra.googlegroups.com...
Hi all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.
The C++ standardization commitee is working with some garbage collection
related proposals,
although no official garbage collection mechanism will be included in C++0x.
It is not yet clear
if the auxillary proposal to make it easier to support garbage collection
via third party libraries
will be approved for C++0x or not.

Nov 15 '08 #6
On 2008-11-15 13:44:20 -0500, "Joe Smith" <un*************@hotmail.comsaid:
>
<pu**********@gmail.comwrote in message
news:22**********************************@a29g2000 pra.googlegroups.com...
Hi
>
>all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

The C++ standardization commitee is working with some garbage
collection related proposals,
although no official garbage collection mechanism will be included in
C++0x. It is not yet clear
if the auxillary proposal to make it easier to support garbage
collection via third party libraries
will be approved for C++0x or not.
It's quite clear, since it was approved at the September meeting. <g>
Search for "safely derived pointer" in the current working draft.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Nov 15 '08 #7

"Pete Becker" <pe**@versatilecoding.comwrote in message
news:2008111514561516807-pete@versatilecodingcom...
On 2008-11-15 13:44:20 -0500, "Joe Smith" <un*************@hotmail.com>
said:
>The C++ standardization commitee is working with some garbage collection
related proposals,
although no official garbage collection mechanism will be included in
C++0x. It is not yet clear
if the auxillary proposal to make it easier to support garbage collection
via third party libraries
will be approved for C++0x or not.

It's quite clear, since it was approved at the September meeting. <g>
Search for "safely derived pointer" in the current working draft.
Roger that, I should have been more clear that it was not clear to me
if the auxillary proposal was included. I'm trying to follow things, but
I am not reading every posted paper, so I may well miss things.

Nov 15 '08 #8
"Chris M. Thomasson" <no@spam.invalidwrote in message
news:7O*************@newsfe24.iad...
<pu**********@gmail.comwrote in message
news:22**********************************@a29g2000 pra.googlegroups.com...
>Hi all,

Is garbage collection possible in C++.

Sure:

http://www.hpl.hp.com/personal/Hans_Boehm/gc

>It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

C++ is a low-level systems language,
C++ is nice because it allows the user to apply just enough of its features
to get the job done. You can use C++ for kernel programming; just not all of
it...

;^D
IMVHO, that's no place for a GC to be...

Nov 15 '08 #9
On Nov 15, 4:57*pm, pushpakul...@gmail.com wrote:
Is garbage collection possible in C++.
Yes and no. There are, in fact, a few constructs which could
break it, and there are potential compiler optimizations which
could prevent it from being used.. In practice, the language
constructs are recognized as poor programming practice, and
something to be avoided, regardless, and compilers don't do
optimizations which would break it, and in fact, it is more or
less widely used; see
http://www.hpl.hp.com/personal/Hans_Boehm/gc/.
It doesn't come as part of language support. Is there any
specific reason for the same due to the way the language is
designed. Or it is discouraged due to some specific reason. If
someone can give inputs on the same, it will be of great help.
More history than any other reasons. It's readily available,
and works, and is being used by a number of people.

--
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
Nov 16 '08 #10
On Nov 15, 5:32*pm, "Chris M. Thomasson" <n...@spam.invalidwrote:
<pushpakul...@gmail.comwrote in message
news:22**********************************@a29g2000 pra.googlegroups.com...
Is garbage collection possible in C++.
Sure:
http://www.hpl.hp.com/personal/Hans_Boehm/gc
It doesn't come as part of language support. Is there any
specific reason for the same due to the way the language is
designed. Or it is discouraged due to some specific reason.
If someone can give inputs on the same, it will be of great
help.
C++ is a low-level systems language, IMVHO, that's no place
for a GC to be...
C++ is a multi-paradigm language, usable in many contexts. If
you're writing kernel code, a garbage collector certainly has no
place; nor do exceptions, for that matter. And if you're
implementing a garbage collector, obviously, you can't use it.
But for most application programs, it's stupid not to.

--
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
Nov 16 '08 #11
On 15/11/08 15:57, pu**********@gmail.com wrote:
Hi all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

Regards,
Pushpa
A related question if I may: Is garbage collection necessary if the
programmer follows a strict RAII design ie. only allocating and
deallocating resources in constructors and destructors? Is garbage
collection just to enable you to program more like Java ie. creating
objects on the heap by using new everywhere? What is the advantage of this?

Java also has the finally block, and I understand this won't be
implemented in C++(0x) any time soon because it's not necessary with
RAII. Can garbage collection in C++ work to the same extent as it does
in Java without the finally block?

--
George Kettleborough
Nov 16 '08 #12
George Kettleborough wrote:
On 15/11/08 15:57, pu**********@gmail.com wrote:
>Hi all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

Regards,
Pushpa

A related question if I may: Is garbage collection necessary if the
programmer follows a strict RAII design ie. only allocating and
deallocating resources in constructors and destructors? Is garbage
collection just to enable you to program more like Java ie. creating
objects on the heap by using new everywhere? What is the advantage of this?
GC and RAII are orthogonal concepts.
Java also has the finally block, and I understand this won't be
implemented in C++(0x) any time soon because it's not necessary with
RAII. Can garbage collection in C++ work to the same extent as it does
in Java without the finally block?
Yes.

--
Ian Collins
Nov 16 '08 #13
On Nov 16, 8:38*am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
On 15/11/08 15:57, pushpakul...@gmail.com wrote:
Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can give
inputs on the same, it will be of great help.
A related question if I may: Is garbage collection necessary
if the programmer follows a strict RAII design ie. only
allocating and deallocating resources in constructors and
destructors?
It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing, it's
generally preferable to use an object directly, with no dynamic
allocation. There are exceptions, of course, but they're a lot
less frequent than people make out. The main motivation for
using dynamic allocation is precisely because the lifetime of
the object must be arbitrary, and doesn't fit any pre-defined
pattern.
Is garbage collection just to enable you to program more like
Java ie. creating objects on the heap by using new everywhere?
What is the advantage of this?
At the lowest level, garbage collection has two major effects:
it allows memory which can no longer be accessed to be reused
(without programmer intervention), and it forbids memory which
can still be accessed from being reused. The first results in
less work for the programmer in a number of specific instances;
it isn't the panacea that some Java proponents would have us
believe, but every little bit helps. The second results in more
robust programs; the memory for one object can't be reused for
another object due to a premature delete. (Premature delete is
a bug that can be exploited to break security, so you definitly
want garbage collection for this reason if your program connects
directly to the Internet.)
Java also has the finally block, and I understand this won't
be implemented in C++(0x) any time soon because it's not
necessary with RAII. Can garbage collection in C++ work to the
same extent as it does in Java without the finally block?
What does garbage collection have to do with the finally block?
For that matter, at the level garbage collection works, what is
the difference between a finally block and the destructor of a
local object?

--
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
Nov 16 '08 #14
On 16/11/08 09:43, James Kanze wrote:
On Nov 16, 8:38 am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
>On 15/11/08 15:57, pushpakul...@gmail.com wrote:
>>Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can give
inputs on the same, it will be of great help.
>A related question if I may: Is garbage collection necessary
if the programmer follows a strict RAII design ie. only
allocating and deallocating resources in constructors and
destructors?

It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing, it's
generally preferable to use an object directly, with no dynamic
allocation. There are exceptions, of course, but they're a lot
less frequent than people make out. The main motivation for
using dynamic allocation is precisely because the lifetime of
the object must be arbitrary, and doesn't fit any pre-defined
pattern.
How would you implement something like a vector without dynamically
allocated memory? I thought dynamically allocated memory was used
because the amount of memory needed can only be decided at run time.
>Is garbage collection just to enable you to program more like
Java ie. creating objects on the heap by using new everywhere?
What is the advantage of this?

At the lowest level, garbage collection has two major effects:
it allows memory which can no longer be accessed to be reused
(without programmer intervention), and it forbids memory which
can still be accessed from being reused. The first results in
less work for the programmer in a number of specific instances;
it isn't the panacea that some Java proponents would have us
believe, but every little bit helps. The second results in more
robust programs; the memory for one object can't be reused for
another object due to a premature delete. (Premature delete is
a bug that can be exploited to break security, so you definitly
want garbage collection for this reason if your program connects
directly to the Internet.)
I suppose what I don't get is why you would ever want to create objects
on the stack. It's something you can't do in Java, and it's much quicker
to create them on the stack plus they get destructed automatically when
the go out of scope.
>Java also has the finally block, and I understand this won't
be implemented in C++(0x) any time soon because it's not
necessary with RAII. Can garbage collection in C++ work to the
same extent as it does in Java without the finally block?

What does garbage collection have to do with the finally block?
For that matter, at the level garbage collection works, what is
the difference between a finally block and the destructor of a
local object?
Well, if you are using new in a try block, and an exception is thrown,
C++ will guarantee the destruction of the pointer and anything else on
the stack but it won't call delete for what you allocated there. I
thought the finally block was to "clean up" any resources you allocated
in the try block, something that isn't necessary if you don't
dynamically allocate resources in there (but instead in the constructors
of objects create there, which are guaranteed to be destroyed).

Maybe I have got this all wrong and I am confusing myself, forgive me
because I'm only just beginning to really learn C++!

--
George Kettleborough
Nov 16 '08 #15
On 2008-11-16 11:17, George Kettleborough wrote:
On 16/11/08 09:43, James Kanze wrote:
>On Nov 16, 8:38 am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
>>On 15/11/08 15:57, pushpakul...@gmail.com wrote:
>>>Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can give
inputs on the same, it will be of great help.
>>A related question if I may: Is garbage collection necessary
if the programmer follows a strict RAII design ie. only
allocating and deallocating resources in constructors and
destructors?

It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing, it's
generally preferable to use an object directly, with no dynamic
allocation. There are exceptions, of course, but they're a lot
less frequent than people make out. The main motivation for
using dynamic allocation is precisely because the lifetime of
the object must be arbitrary, and doesn't fit any pre-defined
pattern.

How would you implement something like a vector without dynamically
allocated memory? I thought dynamically allocated memory was used
because the amount of memory needed can only be decided at run time.
Yes, vectors (and other containers) generally needs dynamic allocations
since you do not know how much memory they will need when they are
created (and you might not have enough space on the stack). But for
these kinds of things memory management is easy since you know when you
need to free the memory (when the container dies). The problem is when
you need to create an object in one place and then pass on ownership to
somewhere else (which in turn might pass on ownership).
>>Java also has the finally block, and I understand this won't
be implemented in C++(0x) any time soon because it's not
necessary with RAII. Can garbage collection in C++ work to the
same extent as it does in Java without the finally block?

What does garbage collection have to do with the finally block?
For that matter, at the level garbage collection works, what is
the difference between a finally block and the destructor of a
local object?

Well, if you are using new in a try block, and an exception is thrown,
C++ will guarantee the destruction of the pointer and anything else on
the stack but it won't call delete for what you allocated there. I
thought the finally block was to "clean up" any resources you allocated
in the try block, something that isn't necessary if you don't
dynamically allocate resources in there (but instead in the constructors
of objects create there, which are guaranteed to be destroyed).
For those kinds of situations you can use auto_ptr or some other smart
pointer which will take care of freeing the allocated memory when they
go out of scope (such as when an exception is thrown). What you can not
do without finally is to free other resources, such as opened files,
unless you build a smart fstream or use guard-classes (can't remember if
that is the correct term). Of course, if the fstream is on the stack you
do not have to worry.

--
Erik Wikström
Nov 16 '08 #16
James Kanze wrote:
It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing, it's
generally preferable to use an object directly, with no dynamic
allocation.
Just because the only place where the memory is deallocated is inside
the destructor, that doesn't mean the memory is *always* deallocated
when the destructor is called. Think about smart pointers and other
similar classes (such as eg. some implementation of std::string which
implements copy-on-write).

Besides, if the object allocates a variable amount of memory, then
allocation and destruction is obviously necessary regardless of how you
use the object.
Nov 16 '08 #17
George Kettleborough wrote:
A related question if I may: Is garbage collection necessary if the
programmer follows a strict RAII design ie. only allocating and
deallocating resources in constructors and destructors? Is garbage
collection just to enable you to program more like Java ie. creating
objects on the heap by using new everywhere? What is the advantage of this?
In my previous job I worked for over 5 years in an extensive C++
project, and in my current job I have done so for over 1.5 years.
Although counting lines of code is not really a perfect measurement of
the amount of work done, and I haven't measured exactly how much code I
have written in total in these two jobs, I wouldn't be surprised if it
was well over 100k LOC. Many of the programs deal with dynamically
allocated memory in rather complex ways.

I have from time to time checked for memory leaks in all my programs
with profilers. How many memory leaks have I had in all these years in
all my C++ programs? Zero. Not even once have I had a single memory leak
in any of my code. During these tests I have found many memory leaks in
third-party libraries (which I had to then fix myself), but none in my
own code.

Also I don't remember even once having accessed freed memory. I have
had a few cases where I have accessed allocated memory out of boundaries
(usually because of an off-by-1 mistake), but even those have been less
than a dozen (mostly in the earlier years), and caught rather quickly.

I really haven't ever felt the need for a GC engine in my work. Could
a GC engine have made my job easier in a few cases? Maybe. I can't say
for sure. At most it could have perhaps saved a bit of writing work, but
not increased the correctness of my code in any way. C++ makes it quite
easy to write safe code when you follow some simple rules.
Java also has the finally block, and I understand this won't be
implemented in C++(0x) any time soon because it's not necessary with
RAII.
I must admit I don't have too much Java programming experience, but if
I'm not completely mistaken, finally-blocks can be used in Java, for
example, to do things like this (in pseudo-java):

void foo()
{
try
{
infile = open_file_here;
perform_lots_of_complicated_stuff_which_might_thro w;
}
finally
{
close(infile);
}
}

Of course in situations like this there just is no need for a
'finally' block in C++, as the same effect can be achieved almost
automatically:

void foo()
{
std::istream infile(whatever);
perform_lots_of_complicated_stuff_which_might_thro w;

// the stream will be automatically closed when foo() is exited
// without having to do anything special to achieve that.
}
Nov 16 '08 #18
Sam
George Kettleborough writes:
On 15/11/08 15:57, pu**********@gmail.com wrote:
>Hi all,

Is garbage collection possible in C++. It doesn't come as part of
language support. Is there any specific reason for the same due to the
way the language is designed. Or it is discouraged due to
some specific reason. If someone can give inputs on the same, it will
be of great help.

Regards,
Pushpa

A related question if I may: Is garbage collection necessary
I'll stop right here. The answer is, obviously, "no", insofar as C++ is
concerned.

The regular posts here about garbage collection in C++ typically come from
newbie programmers who haven't acquired sufficient discipline to keep track
of their own objects. So they seek for a security blanket called "garbage
collection", so they don't have to worry about it, and can proceed to churn
out their spaghetti code without worry, just like they do in Java.

Occasionally some of them stumble across one of several "garbage collection
for C++" libraries, that float out there, and think they've hit paydirt.
Unfortunately, they fail to realize that there are fundamental differences
between C++ and Java, and no "garbage collection" library is going to solve
it.
Is garbage collection just to enable you to program more like Java ie.
creating objects on the heap by using new everywhere?
Yes. And not caring about proper class design, and structure. The "C++ for
dummies" approach.
RAII. Can garbage collection in C++ work to the same extent as it does
in Java without the finally block?
No. Garbage collection in C++ will not work to the same extent, but for
other reasons.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkkgNA4ACgkQx9p3GYHlUOKCDgCeMnVXfBSTAX F3/TOB4y6RsDmd
0egAn0nUJ13zhJyoXTjVQ1mMbQOp8ZP4
=h2EV
-----END PGP SIGNATURE-----

Nov 16 '08 #19
Sam wrote:
>Is garbage collection just to enable you to program more like Java ie.
creating objects on the heap by using new everywhere?

Yes. And not caring about proper class design, and structure. The "C++
for dummies" approach.
Sometimes I get the impression that garbage collection actually causes
people to write *less* modular and more imperative programs. GC doesn't
really encourage encapsulation and modularity.

Sure, you might not get a (permanent) memory leak when you have GC and
you can freely allocate and toss anything you like, but I wonder if this
kind of "irresponsible" programming style doesn't naturally lead to less
modular, less encapsulated programs which are more akin to spaghetti code.
Nov 16 '08 #20
On Nov 15, 7:20 pm, James Kanze <james.ka...@gmail.comwrote:
On Nov 15, 5:32 pm, "Chris M. Thomasson" <n...@spam.invalidwrote:
C++ is a low-level systems language, IMVHO, that's no place
for a GC to be...

C++ is a multi-paradigm language, usable in many contexts. If
you're writing kernel code, a garbage collector certainly has no
place; nor do exceptions, for that matter. And if you're
implementing a garbage collector, obviously, you can't use it.
But for most application programs, it's stupid not to.
RAII, RRID, STL containers, automatic variables, value-based design,
and other software design patterns have served exceptionally well in
eliminating both the need and the want for GC in my work.

Furthermore almost every memory management problem I remember finding
recently that would have gone unnoticed in a GC environment was not
only
a resource management problem but was also a logical or design flaw
that
was much better found than swept under the GC rug.

Finally, the deterministic design patterns we employ to eliminate
memory
management problems also apply directly to other scare resources such
as
ports, handles, connections, locks, etc. The same cannot be said for
GC.

How does the above make me stupid for not using GC?

KHD

Nov 16 '08 #21
On Nov 16, 7:24 am, Juha Nieminen <nos...@thanks.invalidwrote:
George Kettleborough wrote:
A related question if I may: Is garbage collection necessary if the
programmer follows a strict RAII design ie. only allocating and
deallocating resources in constructors and destructors? Is garbage
collection just to enable you to program more like Java ie. creating
objects on the heap by using new everywhere? What is the advantage of this?

In my previous job I worked for over 5 years in an extensive C++
project, and in my current job I have done so for over 1.5 years.
Although counting lines of code is not really a perfect measurement of
the amount of work done, and I haven't measured exactly how much code I
have written in total in these two jobs, I wouldn't be surprised if it
was well over 100k LOC. Many of the programs deal with dynamically
allocated memory in rather complex ways.

I have from time to time checked for memory leaks in all my programs
with profilers. How many memory leaks have I had in all these years in
all my C++ programs? Zero. Not even once have I had a single memory leak
in any of my code. During these tests I have found many memory leaks in
third-party libraries (which I had to then fix myself), but none in my
own code.

Also I don't remember even once having accessed freed memory. I have
had a few cases where I have accessed allocated memory out of boundaries
(usually because of an off-by-1 mistake), but even those have been less
than a dozen (mostly in the earlier years), and caught rather quickly.

I really haven't ever felt the need for a GC engine in my work. Could
a GC engine have made my job easier in a few cases? Maybe. I can't say
for sure. At most it could have perhaps saved a bit of writing work, but
not increased the correctness of my code in any way. C++ makes it quite
easy to write safe code when you follow some simple rules.
My experience echos Juha's almost exactly and I entirely agree
with his conclusion. Futhermore, the determinstic design patterns
that C++ supports help one manage /any/ scarce resource; they are
not limited primarily to memory as GC is. Finally and ironically,
GC can sweep design errors under the rug actually reducing the
semantic correctness of your code rather than improving it.

KHD

Nov 16 '08 #22
although it is not strictly necessary , it has its uses with
concurrent programming
it may get really confusing the manage the lifetime of objects when
multiple threads
accessing them ,deleting an object when another thread making use of
it may cause you
headaches(e.g lock-free data structures). although there are solutions
like thread-safe reference counting or hazard pointers they are either
complex or steep on performance and their use are not widespread. GC
may relieve you there.

Hurcan Solter

Nov 16 '08 #23
On Nov 16, 11:17 am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
On 16/11/08 09:43, James Kanze wrote:
On Nov 16, 8:38 am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
On 15/11/08 15:57, pushpakul...@gmail.com wrote:
>Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can
give inputs on the same, it will be of great help.
A related question if I may: Is garbage collection
necessary if the programmer follows a strict RAII design
ie. only allocating and deallocating resources in
constructors and destructors?
It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing,
it's generally preferable to use an object directly, with no
dynamic allocation. There are exceptions, of course, but
they're a lot less frequent than people make out. The main
motivation for using dynamic allocation is precisely because
the lifetime of the object must be arbitrary, and doesn't
fit any pre-defined pattern.
How would you implement something like a vector without
dynamically allocated memory? I thought dynamically allocated
memory was used because the amount of memory needed can only
be decided at run time.
That's certainly one possible reason. It doesn't affect
application code too often, however, because it's already
handled by things like std::vector. If you're implementing
something like the standard library, my comments probably don't
apply. But I doubt that that's the case for most of us.
Is garbage collection just to enable you to program more
like Java ie. creating objects on the heap by using new
everywhere? What is the advantage of this?
At the lowest level, garbage collection has two major
effects: it allows memory which can no longer be accessed to
be reused (without programmer intervention), and it forbids
memory which can still be accessed from being reused. The
first results in less work for the programmer in a number of
specific instances; it isn't the panacea that some Java
proponents would have us believe, but every little bit
helps. The second results in more robust programs; the
memory for one object can't be reused for another object due
to a premature delete. (Premature delete is a bug that can
be exploited to break security, so you definitly want
garbage collection for this reason if your program connects
directly to the Internet.)
I suppose what I don't get is why you would ever want to
create objects on the stack. It's something you can't do in
Java, and it's much quicker to create them on the stack plus
they get destructed automatically when the go out of scope.
I'm not sure I understand what you're saying. You seem to be
contradicting yourself; I suspect that you left out a word
somewhere, but I'm not sure where.

Anyway, unlike Java, C++ has full support for value types, and
you should use them whenever appropriate. In practice, most
objects will be on the stack.
Java also has the finally block, and I understand this
won't be implemented in C++(0x) any time soon because it's
not necessary with RAII. Can garbage collection in C++ work
to the same extent as it does in Java without the finally
block?
What does garbage collection have to do with the finally
block? For that matter, at the level garbage collection
works, what is the difference between a finally block and
the destructor of a local object?
Well, if you are using new in a try block, and an exception is
thrown, C++ will guarantee the destruction of the pointer and
anything else on the stack but it won't call delete for what
you allocated there. I thought the finally block was to "clean
up" any resources you allocated in the try block, something
that isn't necessary if you don't dynamically allocate
resources in there (but instead in the constructors of objects
create there, which are guaranteed to be destroyed).
The finally block is there to do any actions that must be
performed, period. Just because you have garbage collection
doesn't mean that the could be other actions which need to be
performed.

In C++, destructors of on stack objects (RAII) do the same job.
They require a bit more coding to use in isolated cases, but in
general cases (which seem to prevail), they ensure that the
"clean-up" code is implemented with the code which causes it to
be required, and make it much more difficult for the client
programmer to forget it.

--
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
Nov 17 '08 #24
On Nov 16, 1:06 pm, Juha Nieminen <nos...@thanks.invalidwrote:
James Kanze wrote:
It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing,
it's generally preferable to use an object directly, with no
dynamic allocation.
Just because the only place where the memory is deallocated is
inside the destructor, that doesn't mean the memory is
*always* deallocated when the destructor is called. Think
about smart pointers and other similar classes (such as eg.
some implementation of std::string which implements
copy-on-write).
But the only thing forcing the delete into a smart pointer buys
you is confuscation? The main reason for using dynamic memory
at the application level (implementing std::Vector is obviously
a different situation) is because you need arbitrary lifetime.
The object's lifetime ends in response to some external event.
The handler for that event does the delete.
Besides, if the object allocates a variable amount of memory,
then allocation and destruction is obviously necessary
regardless of how you use the object.
If you're talking about things like vector or map, they're
already written, so they're not my problem. If you're talking
about dynamically types objects, it's true that this sometimes
leads to dynamic allocation even if the object logically should
have block scope. I've not found the case to be that frequent,
but it certainly occurs. In such cases, std::auto_ptr is your
friend, and the delete will be called by the destructor of the
std::auto_ptr. Cases where a normal user would write a delete
in a destructor are fairly rare, however (although the
compilation firewall idiom would be an obvious exception).

--
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
Nov 17 '08 #25
On Nov 16, 1:24 pm, Juha Nieminen <nos...@thanks.invalidwrote:
George Kettleborough wrote:
A related question if I may: Is garbage collection necessary
if the programmer follows a strict RAII design ie. only
allocating and deallocating resources in constructors and
destructors? Is garbage collection just to enable you to
program more like Java ie. creating objects on the heap by
using new everywhere? What is the advantage of this?
In my previous job I worked for over 5 years in an extensive
C++ project, and in my current job I have done so for over 1.5
years. Although counting lines of code is not really a
perfect measurement of the amount of work done, and I haven't
measured exactly how much code I have written in total in
these two jobs, I wouldn't be surprised if it was well over
100k LOC. Many of the programs deal with dynamically allocated
memory in rather complex ways.
I have from time to time checked for memory leaks in all my
programs with profilers. How many memory leaks have I had in
all these years in all my C++ programs? Zero. Not even once
have I had a single memory leak in any of my code. During
these tests I have found many memory leaks in third-party
libraries (which I had to then fix myself), but none in my own
code.
So how is this different from C? Obviously, you can write C++
code which doesn't leak memory. Just as obviously, you can
write C code which doesn't leak memory. It's just a question of
the effort involved.
Also I don't remember even once having accessed freed memory.
I have had a few cases where I have accessed allocated memory
out of boundaries (usually because of an off-by-1 mistake),
but even those have been less than a dozen (mostly in the
earlier years), and caught rather quickly.
The classical C error: strcpy( malloc( strlen( s ) ), s ):-)?
(Back when I was working in C, if someone came to me because
their code was crashing in strange ways, this was the first
thing I'd look for.)
I really haven't ever felt the need for a GC engine in my
work. Could a GC engine have made my job easier in a few
cases? Maybe. I can't say for sure. At most it could have
perhaps saved a bit of writing work, but not increased the
correctness of my code in any way. C++ makes it quite easy to
write safe code when you follow some simple rules.
Yes and no. C++ certainly provides a number of tools which can
be used to improve safety. It doesn't require their use,
however, and I've seen a lot of programmers which don't use them
systematically. And of course, human beings being what they
are, regardless of the tools or the process, mistakes will
occasionally creap in.

--
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
Nov 17 '08 #26
On Nov 16, 3:54 pm, Sam <s...@email-scan.comwrote:
George Kettleborough writes:
On 15/11/08 15:57, pushpakul...@gmail.com wrote:
Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can
give inputs on the same, it will be of great help.
A related question if I may: Is garbage collection necessary
I'll stop right here. The answer is, obviously, "no", insofar
as C++ is concerned.
It's not necessary, no. For that matter, classes aren't
necessary either. Garbage collection is just a tool: it reduces
programmer workload, and increases the security of the resulting
code.
The regular posts here about garbage collection in C++
typically come from newbie programmers who haven't acquired
sufficient discipline to keep track of their own objects.
Yah. Newbies with 20 years of C++ experience. Newbies who
unlike you actually know what they're doing. (FWIW, one of the
proponents of garbage collection in the C++ standards committee
is Bjarne Stroustrup. And he's got even more C++ experience
than I do.)

If I were in your place, I wouldn't talk about newbies. You've
consistently shown a lack of understanding of even the most
basic issues in your own postings.
So they seek for a security blanket called "garbage
collection", so they don't have to worry about it, and can
proceed to churn out their spaghetti code without worry, just
like they do in Java.
That is, of course, the most obvious bullshit I've ever seen.
There are cases where garbage collection isn't appropriate, and
cases where it is necessary. Both are relatively rare; most of
the time, it will save some programmer effort, and result in
cleaner code, but only to a limited degree.

--
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
Nov 17 '08 #27
On Nov 16, 7:18 pm, Juha Nieminen <nos...@thanks.invalidwrote:
Sam wrote:
Is garbage collection just to enable you to program more
like Java ie. creating objects on the heap by using new
everywhere?
Yes. And not caring about proper class design, and
structure. The "C++ for dummies" approach.
Sometimes I get the impression that garbage collection
actually causes people to write *less* modular and more
imperative programs. GC doesn't really encourage encapsulation
and modularity.
Garbage collection doesn't "encourage" anything. It's just a
tool. To be used when appropriate. I use it whenever I can,
and find that it results in less lines of code and more robust
and maintainable code.

--
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
Nov 17 '08 #28
On Nov 16, 11:46 pm, hurcan solter <hsol...@gmail.comwrote:
although it is not strictly necessary , it has its uses with
concurrent programming it may get really confusing the manage
the lifetime of objects when multiple threads
Attention! Garbage collection does NOT manage the lifetime of
objects. It only manages memory. It's generally useful in
multithreaded environments for performance reasons, but it
doesn't address issues as to which thread has the right to
access which objects when. That problem is completely
orthogonal to how you manage memory (unless you're writing the
memory management code yourself, of course).

--
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
Nov 17 '08 #29
Sam
James Kanze writes:
On Nov 16, 3:54 pm, Sam <s...@email-scan.comwrote:
>George Kettleborough writes:
On 15/11/08 15:57, pushpakul...@gmail.com wrote:
>Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can
give inputs on the same, it will be of great help.
A related question if I may: Is garbage collection necessary
>I'll stop right here. The answer is, obviously, "no", insofar
as C++ is concerned.

It's not necessary, no. For that matter, classes aren't
necessary either. Garbage collection is just a tool: it reduces
So is a shovel. It's also a tool. There are situations where you can use a
shovel to do something useful. C++ isn't one of them.
>The regular posts here about garbage collection in C++
typically come from newbie programmers who haven't acquired
sufficient discipline to keep track of their own objects.

Yah. Newbies with 20 years of C++ experience. Newbies who
Don't get snippy with me, young man. I outrank you by a few years.
unlike you actually know what they're doing. (FWIW, one of the
proponents of garbage collection in the C++ standards committee
is Bjarne Stroustrup. And he's got even more C++ experience
than I do.)
A quick search finds no evidence that he is a "proponent" of garbage
collection. He discusses the subject, but not from a position of advocacy,
and actually argues that there are better techniques available, in C++, than
garbage collection.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkkhXqUACgkQx9p3GYHlUOKS1wCaAohCaSonFc Sien4+WFpNMKCy
pGMAn2vIgCPRBp7GQqcRLvLIRlaBPmrF
=mmy2
-----END PGP SIGNATURE-----

Nov 17 '08 #30
On Nov 17, 1:08 pm, Sam <s...@email-scan.comwrote:
James Kanze writes:
On Nov 16, 3:54 pm, Sam <s...@email-scan.comwrote:
George Kettleborough writes:
On 15/11/08 15:57, pushpakul...@gmail.com wrote:
Is garbage collection possible in C++. It doesn't come
as part of language support. Is there any specific
reason for the same due to the way the language is
designed. Or it is discouraged due to some specific
reason. If someone can give inputs on the same, it will
be of great help.
A related question if I may: Is garbage collection necessary
I'll stop right here. The answer is, obviously, "no",
insofar as C++ is concerned.
It's not necessary, no. For that matter, classes aren't
necessary either. Garbage collection is just a tool: it
reduces

So is a shovel. It's also a tool. There are situations where
you can use a shovel to do something useful. C++ isn't one of
them.
You might try a better analogy. Shovels aren't used in
programming in general (although there are more than a few
programs that I would like to bury). Garbage collection is
useful in C++, and in fact, is actively being used by a number
of programmers.
The regular posts here about garbage collection in C++
typically come from newbie programmers who haven't acquired
sufficient discipline to keep track of their own objects.
Yah. Newbies with 20 years of C++ experience. Newbies who
Don't get snippy with me, young man. I outrank you by a few
years.
If you did, you'd be retired. (The first machine I ever
programmed was an IBM 1401. Beat that if you can:-).)
unlike you actually know what they're doing. (FWIW, one of the
proponents of garbage collection in the C++ standards committee
is Bjarne Stroustrup. And he's got even more C++ experience
than I do.)
A quick search finds no evidence that he is a "proponent" of
garbage collection.
Have you checked in the discussions on the mail reflectors of
the standardization group? He's more interested in other
aspects, but has expressed himself in favor of garbage
collection on several occasions.

Note that this is an evolution in his position (due, I suspect,
to an evolution in garbage collection technolgy); before 1990,
he doubtlessly could have added it without really asking anyone.
But the technology available before 1990 is a far cry from what
is available today.
He discusses the subject, but not from a position of advocacy,
and actually argues that there are better techniques
available, in C++, than garbage collection.
There are certainly better techniques for some things. For
others, not necessarily. Anything which reduces the amount of
code I have to write myself is a good thing; there are enough
real problems in my applications that I don't have to
artificially create extra work just to keep me busy. And like
all techniques, it can easily be abused, but the fact that
something can be abused isn't a reason for not including it in
C++.

The only real problem garbage collection has is that it has been
presented as a panacea by some (not all) Java proponents; I've
actually been told that you couldn't have memory leaks in Java,
because of garbage collection (at the same time that Sun was
admitting to serious memory leaks in Swing). If you expect
garbage collection to solve every problem, you're going to be
disappointed. But that's not a problem with garbage collection;
that's a problem with your expectations. (And it's not really
unlike many of the postings here on the subject of smart
pointers.)

--
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
Nov 17 '08 #31

"James Kanze" <ja*********@gmail.comwrote in message
news:39**********************************@w1g2000p rk.googlegroups.com...
On Nov 16, 3:54 pm, Sam <s...@email-scan.comwrote:
[...]
So they seek for a security blanket called "garbage
collection", so they don't have to worry about it, and can
proceed to churn out their spaghetti code without worry, just
like they do in Java.
That is, of course, the most obvious bullshit I've ever seen.
There are cases where garbage collection isn't appropriate, and
cases where it is necessary.
Humm.. Can you give an example or two of a scenario in which a GC is
absolutely required/necessary? For some reason, I can't seem to think of one
off the top of my head. What am I missing? Perhaps I misunderstand your use
of the word "necessary"...

Both are relatively rare; most of
the time, it will save some programmer effort, and result in
cleaner code, but only to a limited degree.
I have seen a couple of cases in which a GC covered up more than a "simple
memory leak". Simple example... What if the memory leak was entangled in a
logic error that sometimes caused weird execution results. If the programmer
was alerted to the memory leak, perhaps he/she could have noticed the logic
error as well. Of course, this is highly contrived case. However, it can
occur.

One bad thing about GC is that it sometimes pulls programmers into a false
sense of security, and they end up creating a sloppy design. This is NOT the
fault of the GC, but of the lazy programmer. One can create efficiently
engineered programs _and_ use a GC at the same time.

Nov 17 '08 #32
James Kanze wrote:
So how is this different from C?
C++ makes it much easier to write safe code, and following the
principles which make code safer is much simpler. In other words, there
are lots of situations where you simply don't have to worry about
leakages in any way in C++, while you do have to worry about then in C
because C doesn't help automatizing.

For example, if I instantiate an std::istream at the beginning of a
function, I just don't have to care about closing that file handle at
all. The std::istream object does it automatically for me completely
regardless of where, when and how the function in question is exited,
and regardless of how many exit points it might have. This is not the
case in C, where you always have to be very careful to not to leak (a
file handle in this case).

A garbage collection engine would certainly be much more useful when
programming in C because in C it requires a lot more work to write safe
code, and a GC engine can help a lot in that. In C++ it's my personal
feeling that a GC engine is not *that* useful.

(Of course regardless of having a GC, you can still leak file handles.)
Nov 17 '08 #33
James Kanze wrote:
>Sometimes I get the impression that garbage collection
actually causes people to write *less* modular and more
imperative programs. GC doesn't really encourage encapsulation
and modularity.

Garbage collection doesn't "encourage" anything.
I tend to disagree. Garbage collection encourages writing
"irresponsible" code. By this I mean that since there's no need for
objects to have (memory handling) responsibilities, it easily leads to
the programmer not creating such objects at all, which in turn leads to
a more imperative style of programming, rather than a more modular style.

Some people may (and do) argue that this is a good thing, but I
wouldn't be so sure. Granted, you won't leak memory (well, not
permanently at least), but your code may suffer from spaghettification
just because you were too lazy to actually write some modules rather
than writing "raw" code.

And no, this doesn't mean *all* programmers using a GC'd language
suffer from this.
It's just a tool. To be used when appropriate.
Well, if it would be a *choice*, then it wouldn't be so bad. There are
languages, however, where you are force-fed and you have no choice.
Nov 17 '08 #34
"Juha Nieminen" <no****@thanks.invalidwrote in message
news:Qw**************@read4.inet.fi...
James Kanze wrote:
>So how is this different from C?

C++ makes it much easier to write safe code, and following the
principles which make code safer is much simpler. In other words, there
are lots of situations where you simply don't have to worry about
leakages in any way in C++, while you do have to worry about then in C
because C doesn't help automatizing.

For example, if I instantiate an std::istream at the beginning of a
function, I just don't have to care about closing that file handle at
all. The std::istream object does it automatically for me completely
regardless of where, when and how the function in question is exited,
and regardless of how many exit points it might have. This is not the
case in C, where you always have to be very careful to not to leak (a
file handle in this case).
Closing a file handle in a dtor can be _very_ problematic indeed; read here:

http://groups.google.com/group/comp....97ab562016d016

A garbage collection engine would certainly be much more useful when
programming in C because in C it requires a lot more work to write safe
code, and a GC engine can help a lot in that. In C++ it's my personal
feeling that a GC engine is not *that* useful.

(Of course regardless of having a GC, you can still leak file handles.)
Nov 17 '08 #35

"Chris M. Thomasson" <no@spam.invalidwrote in message
news:lE*****************@newsfe06.iad...
"Juha Nieminen" <no****@thanks.invalidwrote in message
news:Qw**************@read4.inet.fi...
>James Kanze wrote:
>>So how is this different from C?

C++ makes it much easier to write safe code, and following the
principles which make code safer is much simpler. In other words, there
are lots of situations where you simply don't have to worry about
leakages in any way in C++, while you do have to worry about then in C
because C doesn't help automatizing.

For example, if I instantiate an std::istream at the beginning of a
function, I just don't have to care about closing that file handle at
all. The std::istream object does it automatically for me completely
regardless of where, when and how the function in question is exited,
and regardless of how many exit points it might have. This is not the
case in C, where you always have to be very careful to not to leak (a
file handle in this case).

Closing a file handle in a dtor can be _very_ problematic indeed; read
here:

http://groups.google.com/group/comp....97ab562016d016
[...]

refer to the file copy problem in following post:

http://groups.google.com/group/comp....a928139ca349f4

if the system specific internal call to close the file fails in the dtor of
the higher level file object, well, then the shi% will hit the fan;
permanent data loss! Ouch.

:^/

Nov 17 '08 #36

"Juha Nieminen" <no****@thanks.invalidschreef in bericht
news:PC***************@read4.inet.fi...
James Kanze wrote:
>>Sometimes I get the impression that garbage collection
actually causes people to write *less* modular and more
imperative programs. GC doesn't really encourage encapsulation
and modularity.

Garbage collection doesn't "encourage" anything.

I tend to disagree. Garbage collection encourages writing
"irresponsible" code. By this I mean that since there's no need for
objects to have (memory handling) responsibilities, it easily leads to
the programmer not creating such objects at all, which in turn leads to
a more imperative style of programming, rather than a more modular style.
Are saying that people that can't make proper programs using garbage
collection will make good programs without gc?

Nov 17 '08 #37
Sam
James Kanze writes:
On Nov 17, 1:08 pm, Sam <s...@email-scan.comwrote:
>James Kanze writes:
It's not necessary, no. For that matter, classes aren't
necessary either. Garbage collection is just a tool: it
reduces

So is a shovel. It's also a tool. There are situations where
you can use a shovel to do something useful. C++ isn't one of
them.

You might try a better analogy. Shovels aren't used in
programming in general (although there are more than a few
programs that I would like to bury). Garbage collection is
useful in C++, and in fact, is actively being used by a number
of programmers.
Garbage collection is as useful for C++ as a fifth leg would be useful to a
dog. A dog with five legs might find some use for the extra one, but most of
the time it would just get in the way.

Some people may find some cockamamie "garbage collection library" useful,
but many more do not. Furthermore, there are also people who also find
intermediate code generators useful too. Specifically ones that swallow some
glob of XML, and spew out robo-generate spaghetti code that does something
else XML-related. It's useful to a small minority, because it allows them to
put their brain in "park", and not bother learning how the stuff should
work. Which leaves them completely helpless if the end result does not work
as expected, since they have no clue how the spaghetti code works, and
what's wrong with it.
>He discusses the subject, but not from a position of advocacy,
and actually argues that there are better techniques
available, in C++, than garbage collection.

There are certainly better techniques for some things. For
others, not necessarily. Anything which reduces the amount of
code I have to write myself is a good thing; there are enough
There is no such magic wand that one can wave, and make a bunch of code
disappear. Anyone who thinks that is fooling themselves. Garbage
collection-based design results in larger memory requirements, greater
resources, and slower code. That's the tradeoff for not having to bother
with such troublesome tasks as keeping proper track of your objects,
yourself.

But if I wanted to go in that direction, I'd use Java.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkkiAP0ACgkQx9p3GYHlUOJfewCcDVkEpOW+2R uozawkcv70uiuz
Cm8An0p9x8rNG8rpf4LsJfn5X+OlQIJ1
=pd1a
-----END PGP SIGNATURE-----

Nov 17 '08 #38
Sam
Hans Bos writes:
"Juha Nieminen" <no****@thanks.invalidschreef in bericht
news:PC***************@read4.inet.fi...
> I tend to disagree. Garbage collection encourages writing
"irresponsible" code. By this I mean that since there's no need for
objects to have (memory handling) responsibilities, it easily leads to
the programmer not creating such objects at all, which in turn leads to
a more imperative style of programming, rather than a more modular style.

Are saying that people that can't make proper programs using garbage
collection will make good programs without gc?
No, they won't make any programs at all.

Which is a good thing. But only from a theoretical viewpoint. From a
practical viewpoint, those kinds of people should be encourage to spew out
reams of atrocious code. Some people make a pretty good living cleaning up
these messes.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEABECAAYFAkkiAX4ACgkQx9p3GYHlUOL17QCfYoweTy9Fqa ChGt9j+fqi1gNf
HKUAn3uPnSrty66r6nfr4nHG4UulkYc8
=RYEZ
-----END PGP SIGNATURE-----

Nov 17 '08 #39
On Nov 17, 4:18 am, James Kanze <james.ka...@gmail.comwrote:
On Nov 16, 1:24 pm, Juha Nieminen <nos...@thanks.invalidwrote:
I really haven't ever felt the need for a GC engine in my
work. Could a GC engine have made my job easier in a few
cases? Maybe. I can't say for sure. At most it could have
perhaps saved a bit of writing work, but not increased the
correctness of my code in any way. C++ makes it quite easy to
write safe code when you follow some simple rules.

Yes and no. C++ certainly provides a number of tools which can
be used to improve safety. It doesn't require their use,
however, and I've seen a lot of programmers which don't use them
systematically. And of course, human beings being what they
are, regardless of the tools or the process, mistakes will
occasionally creap in.
Yes. However, garbage collection is /only/ going to reclaim
memory, eventually. It's not going to correct the logical and
potentially far more serious design bugs that leaked memory
in the first place. In fact, garbage collection can and does
hide bugs exactly by allowing access to objects that should
not be accessed thus actually reducing correctness. How do
you respond to this?

The various C++ techniques that of course are familiar to you
for managing memory deterministically not only help one prevent
garbage memory, they also help one properly manage other scare
resources which garbage collection does nothing for. How do you
respond to this? Is it not better to learn the more general more
comprehensive deterministic resource management paradigms that C++
supports? And to apply them uniformly and widely?
C++ is a multi-paradigm language, usable in many contexts. If
you're writing kernel code, a garbage collector certainly has
no place; nor do exceptions, for that matter. And if you're
implementing a garbage collector, obviously, you can't use it.
But for most application programs, it's stupid not to.
RAII, RRID, STL containers, automatic variables, value types,
and other software design patterns have served exceptionally
well in eliminating both the need and the want for GC for me.

Furthermore almost every memory management problem I remember
finding recently that would have gone unnoticed with GC in use,
was not only a resource management problem but was also a flaw
in logic or design that was much better found than swept under
the GC rug.

Finally, the deterministic design patterns C++ supports for
memory management also apply directly to other scare resources
such as ports, handles, connections, locks, etc. The same cannot
be said for GC.

In light of the above, why is it "stupid" not to use GC?

KHD
Nov 18 '08 #40
On Nov 17, 4:28 am, James Kanze <james.ka...@gmail.comwrote:
On Nov 16, 11:46 pm, hurcan solter <hsol...@gmail.comwrote:
although it is not strictly necessary , it has its uses with
concurrent programming it may get really confusing the manage
the lifetime of objects when multiple threads

Attention! Garbage collection does NOT manage the lifetime of
objects. It only manages memory.
Attention! In practice the above is FALSE! If it were correct
there would not have been the rather lengthy discussion recently
in comp.lang.c++.moderated among a few of the world's foremost
C++ experts regarding "zombie" states etc.

http://groups.google.com/group/comp....79ef911de670f/

(Don't be fooled by the topic. It was a Trojan Horse bearing the
gift of GC. For example see the subthread starting with post 63.
If the link fails search for "throwing default constructors".)

When one tries to divorce, in practical terms, the concepts of
object "lifetime" and object "storage" the can opens and spills
worms all over your language model. Since you did not post in
that recent thread I'm not sure what your solution for

"destroyed but not deallocated"

is. If you have one please post it so that Andrei and the like
can employ (or at least research) it.

KHD

Nov 18 '08 #41
On Nov 17, 8:29 pm, Juha Nieminen <nos...@thanks.invalidwrote:
James Kanze wrote:
Sometimes I get the impression that garbage collection
actually causes people to write *less* modular and more
imperative programs. GC doesn't really encourage encapsulation
and modularity.
Garbage collection doesn't "encourage" anything.
I tend to disagree.
Sorry, but it's a statement of fact. Garbage collection is just
a tool; a piece of code. It can't encourage or discourage
anything.

At one time, some proponents of garbage collection were trying
to sell it as a silver bullet. Or rather, to sell it as part of
a larger package which was presented as a silver bullet.
Serious programmers, of course, no that silver bullets don't
exist.
Garbage collection encourages writing "irresponsible" code.
How can some code in your machine encourage anything. You're
attributing motives and characterists of a living being to an
inanimate object. (There's a name for this, but I've forgotten
it. But it's frequent among programmers---how often do you hear
a programmer talk about a "bug" which "crept into" his software,
rather than to say "I made an error"?)
By this I mean that since there's no need for objects to have
(memory handling) responsibilities, it easily leads to the
programmer not creating such objects at all, which in turn
leads to a more imperative style of programming, rather than a
more modular style.
Sorry, but I can't follow this at all. Garbage collection
certainly reduces the need for objects dedicated uniquely to
memory management, but how does this relate to whether code is
imperative or not.

For that matter, there are cases where an imperative style is
good. One size doesn't fit all; you need to use the appropriate
technique, among all of those available, to solve each problem.
In practice, garbage collection makes OO (OO in the sense of
using polymorphic objects) easier; polymorphic objects generally
have to be allocated dynamically (supposing the exact type not
known at compile time).
Some people may (and do) argue that this is a good thing,
What is a good thing?
but
I wouldn't be so sure. Granted, you won't leak memory (well,
not permanently at least),
Where to you get this. Garbage collection doesn't mean that you
won't leak memory. The bug list for Java contains a number of
memory leaks.
but your code may suffer from spaghettification just because
you were too lazy to actually write some modules rather than
writing "raw" code.
And no, this doesn't mean *all* programmers using a GC'd
language suffer from this.
Programmers who want to write spaghetti will write spaghetti.
With or without garbage collection. You're not going to claim
that C and C++ encourage readability, I hope. Not with the
preprocessor, pointer arithmetic, and their declaration syntax.
It's just a tool. To be used when appropriate.
Well, if it would be a *choice*, then it wouldn't be so bad.
There are languages, however, where you are force-fed and you
have no choice.
We're talking about C++ here. Where the guiding principle is
that the programmer knows best. And the philosophy is to give
him as many different tools as possible, for him to choose what
it best at any given time.

Other languages have other philosophies. In some cases, what
they were trying to force-feed you wasn't actually a bad idea.
(I'm thinking of Eiffel and programming by contract.) But even
then, experience (mine, anyway) shows that it doesn't pay off in
the long run. As the technology (the tools set) becomes more
widely used, we learn more about it, and change our ideas
somewhat about how to use it.

There are doubtlessly applications where garbage collection
shouldn't be used at all. (There are, in fact, applications
where dynamic memory shouldn't be used at all.) And it
certainly isn't the solution for everything. But the fact that
a technology can be misused has never been an argument against
introducing it into C++, provided that it also has advantages
when correctly used.

--
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
Nov 18 '08 #42
On Nov 18, 12:40 am, Sam <s...@email-scan.comwrote:
James Kanze writes:
On Nov 17, 1:08 pm, Sam <s...@email-scan.comwrote:
James Kanze writes:
It's not necessary, no. For that matter, classes aren't
necessary either. Garbage collection is just a tool: it
reduces
So is a shovel. It's also a tool. There are situations
where you can use a shovel to do something useful. C++
isn't one of them.
You might try a better analogy. Shovels aren't used in
programming in general (although there are more than a few
programs that I would like to bury). Garbage collection is
useful in C++, and in fact, is actively being used by a
number of programmers.
Garbage collection is as useful for C++ as a fifth leg would
be useful to a dog. A dog with five legs might find some use
for the extra one, but most of the time it would just get in
the way.
Another ridiculous analogy, which doesn't relate to anything.
Some people may find some cockamamie "garbage collection
library" useful, but many more do not.
Really. Every one I've talked to who's used the Boehm collector
has found it useful.
Furthermore, there are also people who also find intermediate
code generators useful too. Specifically ones that swallow
some glob of XML, and spew out robo-generate spaghetti code
that does something else XML-related. It's useful to a small
minority, because it allows them to put their brain in "park",
and not bother learning how the stuff should work. Which
leaves them completely helpless if the end result does not
work as expected, since they have no clue how the spaghetti
code works, and what's wrong with it.
In other words, if I need to tokenize input, I should write my
tokenizer by hand, rather than use some regular expression based
tool. If I want to test my application, I should write all of
the boiler plate code by hand, rather than using some test
generator. If I want to run a program consisting of machine
instructions, I should write the machine instructions by hand,
rather than using some compiler and linker.

I think you're being a bit silly. And missing the point. Doing
less work (writing less lines of code, etc.) is good.
He discusses the subject, but not from a position of
advocacy, and actually argues that there are better
techniques available, in C++, than garbage collection.
There are certainly better techniques for some things. For
others, not necessarily. Anything which reduces the amount
of code I have to write myself is a good thing; there are
enough
There is no such magic wand that one can wave, and make a
bunch of code disappear. Anyone who thinks that is fooling
themselves. Garbage collection-based design results in larger
memory requirements, greater resources, and slower code.
Than what? In the cases I've actually seen, garbage collection
does result in increased memory use, sometimes significantly,
and this must be taken into account. (But what is cheaper,
memory, or programmer time.) In most cases, it results in the
program running faster, or appearing to. (But of course, you
could manually optimize the non-garbage collected code to do the
same thing.)

--
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
Nov 18 '08 #43
On Nov 17, 6:14 pm, "Chris M. Thomasson" <n...@spam.invalidwrote:
"James Kanze" <james.ka...@gmail.comwrote in message
news:39**********************************@w1g2000p rk.googlegroups.com...
On Nov 16, 3:54 pm, Sam <s...@email-scan.comwrote:
[...]
So they seek for a security blanket called "garbage
collection", so they don't have to worry about it, and can
proceed to churn out their spaghetti code without worry,
just like they do in Java.
That is, of course, the most obvious bullshit I've ever
seen. There are cases where garbage collection isn't
appropriate, and cases where it is necessary.
Humm.. Can you give an example or two of a scenario in which a
GC is absolutely required/necessary?
Off hand, no, but I think Hans Boehm had one.
For some reason, I can't seem to think of one off the top of
my head. What am I missing? Perhaps I misunderstand your use
of the word "necessary"...
Sort of. The statement wasn't meant to be taken as giving any
absolute limits, but rather simply to indicate that there is a
great range. (Of course, if you have limited resources to
develop the code, and garbage collection means you need to write
less lines of code---which it usually does---you could argue
that it is necessary to develop the code within budget.)
Both are relatively rare; most of the time, it will save
some programmer effort, and result in cleaner code, but only
to a limited degree.
I have seen a couple of cases in which a GC covered up more
than a "simple memory leak". Simple example... What if the
memory leak was entangled in a logic error that sometimes
caused weird execution results. If the programmer was alerted
to the memory leak, perhaps he/she could have noticed the
logic error as well. Of course, this is highly contrived case.
However, it can occur.
Not with any of the organizations I've worked with. In the ones
which took quality seriously, code review and tests would have
detected the error. In the other ones, the leak likely would
have gone undetected.

Dangling pointers are a different issue. Garbage collection
allows reliable detection of dangling pointers to dynamically
allocated memory (but not to local variables); without garbage
collection, you can't detect the case reliably. And dangling
pointers are a known security risk for programs connecting to an
open network.
One bad thing about GC is that it sometimes pulls programmers
into a false sense of security,
Garbage collection is just a bunch of code. It doesn't "pull"
programmers in any way. Anthropomorphic analogies really don't
apply; code is not a living being.
and they end up creating a sloppy design. This is NOT the
fault of the GC, but of the lazy programmer.
Or the incompetent one. Or the mismanaged one. But programmers
don't need garbage collection to be lazy, incompetent or
mismanaged.
One can create efficiently engineered programs _and_ use a GC
at the same time.
Certainly. And that's why it should be an available option, to
be used as appropriate.

--
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

Nov 18 '08 #44
James Kanze wrote:
On Nov 16, 8:38 am, George Kettleborough
<g.kettleboro...@member.fsf.orgwrote:
>On 15/11/08 15:57, pushpakul...@gmail.com wrote:
>>Is garbage collection possible in C++. It doesn't come as
part of language support. Is there any specific reason for
the same due to the way the language is designed. Or it is
discouraged due to some specific reason. If someone can give
inputs on the same, it will be of great help.
>A related question if I may: Is garbage collection necessary
if the programmer follows a strict RAII design ie. only
allocating and deallocating resources in constructors and
destructors?

It rarely makes sense to allocate memory in constructors and
deallocate in destructors. If that's what you're doing, it's
generally preferable to use an object directly, with no dynamic
allocation. [...]
Except that the latter isn't polymorphic.

Schobi
Nov 18 '08 #45
On Nov 18, 5:57 am, Keith H Duggar <dug...@alum.mit.eduwrote:
On Nov 17, 4:28 am, James Kanze <james.ka...@gmail.comwrote:
On Nov 16, 11:46 pm, hurcan solter <hsol...@gmail.comwrote:
although it is not strictly necessary , it has its uses
with concurrent programming it may get really confusing
the manage the lifetime of objects when multiple threads
Attention! Garbage collection does NOT manage the lifetime
of objects. It only manages memory.
Attention! In practice the above is FALSE!
Apparently, then, you don't even know what garbage collection
does. Garbage collection manages memory. It does NOT manage
object lifetime. The two are different things (and the C++
standard very decisively keeps them separate).
If it were correct there would not have been the rather
lengthy discussion recently in comp.lang.c++.moderated among a
few of the world's foremost C++ experts regarding "zombie"
states etc.
http://groups.google.com/group/comp....browse_frm/thr...
(Don't be fooled by the topic. It was a Trojan Horse bearing
the gift of GC. For example see the subthread starting with
post 63. If the link fails search for "throwing default
constructors".)
When one tries to divorce, in practical terms, the concepts of
object "lifetime" and object "storage" the can opens and
spills worms all over your language model. Since you did not
post in that recent thread I'm not sure what your solution for
"destroyed but not deallocated"
is. If you have one please post it so that Andrei and the like
can employ (or at least research) it.
It's not a recent topic, and Andrei and I have discussed it in
newsgroups in the past, and unless his position has radically
changed, we more or less agree.

But I'm not sure what your question is. It's obvious that in
this case, garbage collection is necessary to protect against
and detect using dangling pointers. The idiom works because
with garbage collection, memory management is decoupled from
object lifetime; because even though the object has ceased to
exist, the memory behind it cannot be reused as long as anyone
has a pointer to it.

--
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
Nov 18 '08 #46
zr
On Nov 17, 11:28*am, James Kanze <james.ka...@gmail.comwrote:
On Nov 16, 11:46 pm, hurcan solter <hsol...@gmail.comwrote:
although it is not strictly necessary , it has its uses with
concurrent programming it may get really confusing the manage
the lifetime of objects when multiple threads

Attention! Garbage collection does NOT manage the lifetime of
objects. *It only manages memory. *It's generally useful in
multithreaded environments for performance reasons, but it
doesn't address issues as to which thread has the right to
access which objects when. *That problem is completely
orthogonal to how you manage memory (unless you're writing the
memory management code yourself, of course).
How can GC improve the performance of a multithreaded application? Can
you show a convincing example?
Nov 18 '08 #47
Keith H Duggar wrote:
Yes. However, garbage collection is /only/ going to reclaim
memory, eventually. It's not going to correct the logical and
potentially far more serious design bugs that leaked memory
in the first place.
Yes, GC does not correct any bugs, you're right about that ;). However,
there are many situations where having to do manual deallocation is just
additional work without any benefit. For example, if you're doing a lot
of tree handling, building trees, throwing them away again etc., you
don't really want to traverse the tree to free all the elements if you
throw it away. Much more convenient to simply "forget" the pointer to
the tree and let automatic memory management wipe it up.
(This is a bit relativized if you have a situation where you need to
have destructors run in tree nodes; in general, the concepts of
destructors and GC don't really work well together, and imho,
destructors are rather an ugly add-hoc hack that stems from the lack of
automatic memory management and because of that unfortunately has firmly
established itself in C++...)
Nov 18 '08 #48
Juha Nieminen wrote:
By this I mean that since there's no need for
objects to have (memory handling) responsibilities, it easily leads to
the programmer not creating such objects at all,
Isn't that a good thing? The best code is the one you don't have to
write. Down with bureaucracy. Creating objects just to keep track of
memory dependencies is... inane?
which in turn leads to
a more imperative style of programming, rather than a more modular style.
Imperative programming and modular programming are orthogonal concepts.
Nov 18 '08 #49
zr wrote:
How can GC improve the performance of a multithreaded application? Can
you show a convincing example?
Many of today's programs (OO or not) have a high
allocation(/deallocation) rate. This means that most objects become
garbage quickly. With many GCs, their collection time is a function of
the amount of live data, that is, they don't have to traverse the
garbage at all. This means in total, in such a situation, there's less
work to do than in a manual deallocation scheme, where all the garbage
is being traversed aswell.
I don't know if multithreading is any factor here; with manual schemes,
you have to do synchronization, too.
Nov 18 '08 #50

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

Similar topics

1
2290
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...
6
810
by: Ganesh | last post by:
Is there a utility by microsoft (or anyone) to force garbage collection in a process without have access to the process code. regards Ganesh
11
2713
by: Rick | last post by:
Hi, My question is.. if Lisp, a 40 year old language supports garbage collection, why didn't the authors of C++ choose garbage collection for this language? Are there fundamental reasons behind...
34
6360
by: Ville Voipio | last post by:
I would need to make some high-reliability software running on Linux in an embedded system. Performance (or lack of it) is not an issue, reliability is. The piece of software is rather simple,...
5
3561
by: Bob lazarchik | last post by:
Hello: We are considering developing a time critical system in C#. Our tool used in Semiconductor production and we need to be able to take meaurements at precise 10.0 ms intervals( 1000...
8
3013
by: mike2036 | last post by:
For some reason it appears that garbage collection is releasing an object that I'm still using. The object is declared in a module and instantiated within a class that is in turn instantiated by...
28
3132
by: Goalie_Ca | last post by:
I have been reading (or at least googling) about the potential addition of optional garbage collection to C++0x. There are numerous myths and whatnot with very little detailed information. Will...
56
3620
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application =...
350
11459
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
7231
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7132
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
7063
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5640
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5059
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new...
0
4720
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3211
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3196
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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

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