473,586 Members | 2,870 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, 7:20 pm, James Kanze <james.ka...@gm ail.comwrote:
On Nov 15, 5:32 pm, "Chris M. Thomasson" <n...@spam.inva lidwrote:
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.or gwrote:
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.
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 objektorientier ter Datenverarbeitu ng
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 objektorientier ter Datenverarbeitu ng
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 objektorientier ter Datenverarbeitu ng
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...@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
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 objektorientier ter Datenverarbeitu ng
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 objektorientier ter Datenverarbeitu ng
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 objektorientier ter Datenverarbeitu ng
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...@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.
>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)

iEYEABECAAYFAkk hXqUACgkQx9p3GY HlUOKS1wCaAohCa SonFcSien4+WFpN MKCy
pGMAn2vIgCPRBp7 GQqcRLvLIRlaBPm rF
=mmy2
-----END PGP SIGNATURE-----

Nov 17 '08 #30

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
7911
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7839
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...
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
8215
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...
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...
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

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.