Garbage collection in C++

P

pushpakulkar

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
 
C

Chris M. Thomasson

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

Juha Nieminen

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

Joe Smith

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

Joe Smith

Pete Becker said:
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.
 
C

Chris M. Thomasson

Chris M. Thomasson said:
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
 
J

James Kanze

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

James Kanze

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

George Kettleborough

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

Ian Collins

George said:
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.
 
J

James Kanze

On 15/11/08 15:57, (e-mail address removed) 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?

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

George Kettleborough

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.
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.
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++!
 
E

Erik Wikström

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).
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.
 
J

Juha Nieminen

James said:
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.
 
J

Juha Nieminen

George said:
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_throw;
}
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_throw;

// the stream will be automatically closed when foo() is exited
// without having to do anything special to achieve that.
}
 
J

Juha Nieminen

Sam said:
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.
 
K

Keith H Duggar

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
 
K

Keith H Duggar

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
 
H

hurcan solter

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top