473,597 Members | 2,040 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 7766
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...@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
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 objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Nov 17 '08 #31

"James Kanze" <ja*********@gm ail.comwrote in message
news:39******** *************** ***********@w1g 2000prk.googleg roups.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
"irresponsi ble" code. By this I mean that since there's no need for
objects to have (memory handling) responsibilitie s, 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 spaghettificati on
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.in et.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.invali dwrote in message
news:lE******** *********@newsf e06.iad...
"Juha Nieminen" <no****@thanks. invalidwrote in message
news:Qw******** ******@read4.in et.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.i net.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
"irresponsi ble" code. By this I mean that since there's no need for
objects to have (memory handling) responsibilitie s, 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)

iEYEABECAAYFAkk iAP0ACgkQx9p3GY HlUOJfewCcDVkEp OW+2Ruozawkcv70 uiuz
Cm8An0p9x8rNG8r pf4LsJfn5X+OlQI J1
=pd1a
-----END PGP SIGNATURE-----

Nov 17 '08 #38
Sam
Hans Bos writes:
"Juha Nieminen" <no****@thanks. invalidschreef in bericht
news:PC******** *******@read4.i net.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) responsibilitie s, 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)

iEYEABECAAYFAkk iAX4ACgkQx9p3GY HlUOL17QCfYoweT y9FqaChGt9j+fqi 1gNf
HKUAn3uPnSrty66 r6nfr4nHG4UulkY c8
=RYEZ
-----END PGP SIGNATURE-----

Nov 17 '08 #39
On Nov 17, 4:18 am, James Kanze <james.ka...@gm ail.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 deterministical ly 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

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

Similar topics

1
2312
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 period of time that an application may lock up while garbage collection is processing. Thanks!
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 wondering :)
34
6395
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 something hardware- related which will get its own driver written in C.
5
3587
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 interfere with our measurement results. I have looked over the garbage collection mechanism and see no...
8
3030
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 yanks it out from under my processing. Is there a way to ensure an instantiated object cannot be freed...
28
3154
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 raised (especially due to pointer abuse). Is a GC for C++ just a pipe dream or is there a lot of work...
56
3650
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
11613
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 days gone by?
0
7885
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8271
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8380
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8031
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8258
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6686
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 projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5847
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3881
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3923
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.