473,806 Members | 2,895 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting around garbage collection

I've been messing around with a C++ application on Xbox, and have been
encountering problems with my objects getting garbage collected when
they go out of scope, but before I'm actually done using them. I'm not
really familiar with how this works in C++, since I first learned C,
then Java, and never really spent a lot of time learning C++ other
than applying Java concepts to C++'s syntax. Here's my problem:

I have a function (doesn't matter if it's a class method or just a
random function) which instantiates an object of the Rect class by
calling its constructor ( Rect asdf = Rect(100, 200, ... ); ) and then
returns a pointer to asdf. However, once the function returns, asdf
gets garbage collected (at least, I'm assuming that's what happens,
since it's the only explanation I can think of for...) and my returned
pointer is useless, and breaks my app if I try to use it. I guess in C
I would have gotten around this by using malloc() to allocate the
memory for asdf, but since I'm using C++ that would cause my
constructor to not get called. There are probably a couple things
about constructors in C++ I don't know that would help out here, so if
anyone can help me out with that or suggest other ideas about how to
fix this problem I'd appreciate it. Thanks in advance.

Bryan
Jul 22 '05 #1
3 1437

"Bryan" <ba*****@calpol y.edu> wrote
I've been messing around with a C++ application on Xbox, and have
been
encountering problems with my objects getting garbage collected when
they go out of scope,
If you're talking about standard C++, I think you mean "destructed " rather
than "garbage collected."
but before I'm actually done using them. I'm not
really familiar with how this works in C++, since I first learned C,
then Java, and never really spent a lot of time learning C++ other
than applying Java concepts to C++'s syntax.
If it's really just going out of scope, then you would have the same problem
in C as well.
Here's my problem:

I have a function (doesn't matter if it's a class method or just a
random function) which instantiates an object of the Rect class by
calling its constructor ( Rect asdf = Rect(100, 200, ... ); ) and then
returns a pointer to asdf. However, once the function returns, asdf
gets garbage collected (at least, I'm assuming that's what happens,
since it's the only explanation I can think of for...) and my returned
pointer is useless, and breaks my app if I try to use it.
No, it's not garbage collected, it simply went out of scope and you've
returned a dangling pointer. Dangling pointers are a Bad Thing that cause
undefined behavior (like program crashes).
I guess in C
I would have gotten around this by using malloc() to allocate the
memory for asdf, but since I'm using C++ that would cause my
constructor to not get called.


Okay, then you need to use C++'s "new". But you also need to learn about
memory allocation and pointer issues in C++. A use of new generally
requires a corresponding "delete". Better yet, you should use a smart
pointer. Take a look at the C++ FAQ at parashift.com, or better yet get
yourself a good introductory C++ book like Koenig and Moo's Accelerated C++.

Best regards,

Tom
Jul 22 '05 #2
Thomas Tutone wrote:
"Bryan" <ba*****@calpol y.edu> wrote

I've been messing around with a C++ application on Xbox, and have
been
encounterin g problems with my objects getting garbage collected when
they go out of scope,

If you're talking about standard C++, I think you mean "destructed " rather
than "garbage collected."

but before I'm actually done using them. I'm not
really familiar with how this works in C++, since I first learned C,
then Java, and never really spent a lot of time learning C++ other
than applying Java concepts to C++'s syntax.

If it's really just going out of scope, then you would have the same problem
in C as well.

Here's my problem:

I have a function (doesn't matter if it's a class method or just a
random function) which instantiates an object of the Rect class by
calling its constructor ( Rect asdf = Rect(100, 200, ... ); ) and then
returns a pointer to asdf. However, once the function returns, asdf
gets garbage collected (at least, I'm assuming that's what happens,
since it's the only explanation I can think of for...) and my returned
pointer is useless, and breaks my app if I try to use it.

No, it's not garbage collected, it simply went out of scope and you've
returned a dangling pointer. Dangling pointers are a Bad Thing that cause
undefined behavior (like program crashes).

I guess in C
I would have gotten around this by using malloc() to allocate the
memory for asdf, but since I'm using C++ that would cause my
constructor to not get called.

Okay, then you need to use C++'s "new". But you also need to learn about
memory allocation and pointer issues in C++. A use of new generally
requires a corresponding "delete". Better yet, you should use a smart
pointer. Take a look at the C++ FAQ at parashift.com, or better yet get
yourself a good introductory C++ book like Koenig and Moo's Accelerated C++.

Best regards,

Tom

What Tom said, but I'd like to point out that the stack is your friend.

If Rect's are not expensive to copy, it's probably faster to return your
function's result by value, rather than by reference. Then you don't
have to use pointers, new, or delete. E.g.:

namespace Shapes
{
class Rect { }

Rect make_rect( )
{
Rect result;
/* ... */
return result;
}
}

int main( )
{
using namespace Shapes;

Rect rect = make_rect( );
}
Jul 22 '05 #3
ba*****@calpoly .edu (Bryan) wrote in message news:<ff******* *************** ****@posting.go ogle.com>...
I've been messing around with a C++ application on Xbox, and have been
encountering problems with my objects getting garbage collected when
they go out of scope, but before I'm actually done using them.
There is no garbage collection in C++, unless you talk about managed
C++ in the .NET world.
I have a function (doesn't matter if it's a class method or just a
random function) which instantiates an object of the Rect class by
calling its constructor ( Rect asdf = Rect(100, 200, ... ); ) and then
returns a pointer to asdf. However, once the function returns, asdf
gets garbage collected (at least, I'm assuming that's what happens,
since it's the only explanation I can think of for...)
As you invoked "Rect asdf = Rect()" and not "Rect* asdfPtr = new
Rect()", your Rect instance sits on the stack, and will be lost as
soon as the function returns. The pointer returned will point to
nirvana by then. You could return asdf itself, so it will be passed
back to the caller, and the caller can then assign it to another Rect
instance (this would involve a copy constructor invocation though).
There are probably a couple things
about constructors in C++ I don't know that would help out here, so if
anyone can help me out with that or suggest other ideas about how to
fix this problem I'd appreciate it. Thanks in advance.


You must distinguish between objects on the stack (which run out of
scope) and the heap, where dynamic memory allocation happens (as by
invoking malloc resp. new), and where you are responsible for free'ing
/ deleting them as soon as they are not longer needed.

If you come from the Java world, consider that there all objects are
heap-based and garbage-collected (simple datatypes are stack-based),
which is not the case in C++.

Kind regards,
Arno Huetter
Jul 22 '05 #4

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

Similar topics

1
2340
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!
0
1894
by: Andrew | last post by:
When will .NET have a low-pause-time garbage collector A low-pause-time garbage collector would greatly improve .NET's ability to serve as a platform for soft real-time systems. It doesn't have to be perfect. For example, I'd be happy with something where there was at most one pause per second, each pause was less than .2 seconds, and half the process's memory was inaccessible to the application due to garbage collection management It...
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
2
1768
by: Oculus | last post by:
Before I get into the question -- I know .NET isn't the right solution for this app but it's part of my clients requirements and writing this in C++ isn't an option. That being said -- my app is a stock ticker using the managed DirectX libraries and the animation needs to be perfectly smooth. Problem is that the garbage collector will kick in from time to time and cause my render thread to miss a frame and makes it look like hell (even at...
11
2741
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
6438
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
3620
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...
14
2278
by: John J. Hughes II | last post by:
Using the below code I am send multiple sterilized object across an IP port. This works fine if only one object is received at a time but with packing sometimes there is more then one object or half an object in the received data. If I place the data in a memory stream on the received side is there a way to determine where one ends and the next one start? Since the deserializer stream seems to move the pointer I am trying to look at the...
158
7919
by: pushpakulkar | last post by:
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
0
9719
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9597
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
10620
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...
1
10372
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,...
1
7650
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
6877
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5546
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...
1
4329
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
2
3851
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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

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