473,586 Members | 2,817 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
158 7764
On Nov 15, 4:57*pm, pushpakul...@gm ail.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 objektorientier ter Datenverarbeitu ng
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**********@gm ail.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**********@gm ail.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.or gwrote:
On 15/11/08 15:57, pushpakul...@gm ail.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 objektorientier ter Datenverarbeitu ng
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.or gwrote:
>On 15/11/08 15:57, pushpakul...@gm ail.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.o rgwrote:
>>On 15/11/08 15:57, pushpakul...@gm ail.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
discourage d 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_st uff_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_st uff_which_might _throw;

// 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**********@gm ail.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)

iEYEABECAAYFAkk gNA4ACgkQx9p3GY HlUOKCDgCeMnVXf BSTAXF3/TOB4y6RsDmd
0egAn0nUJ13zhJy oXTjVQ1mMbQOp8Z P4
=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 "irresponsi ble" programming style doesn't naturally lead to less
modular, less encapsulated programs which are more akin to spaghetti code.
Nov 16 '08 #20

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

Similar topics

1
2310
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 then throws them away and then monitors the garbage collection and store statistics on it, preferably in C#. I want to know what is the longest...
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
2718
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 this? Is it because C is generally a 'low level' language and they didn't want garbage collection to creep into C++ and ruin everything? Just...
34
6394
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, probably a few hundred lines of code in Python. There is a need to interact with network using the socket module, and then probably a need to do...
5
3586
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 measurement exactly 10 ms apart. In the future this may decrease to 5ms ). I am concerned that if garbage collection invokes during this time it may...
8
3029
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 the mainline. The class that instantiated the object in question is definitely still in existence at the point garbage collection swoops in and...
28
3153
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 this work be library based or language based and will it be based on that of managed C++? Then of course there are the finer technical questions...
56
3649
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 = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
350
11612
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 one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to...
0
8338
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7954
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6610
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5390
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3836
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1179
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.