user228058
user228058

Reputation: 475

Unmanaged C++ Garbage Collection help

I'm a .net programmer, without much experience with unmanaged code. I've been adding modifications and additions to an unmanaged project, and everything is functioning just fine. Can you give me some pointers as to what kind of code/objects I need to be concerned about in regard to garbage collection?

TIA

Upvotes: 3

Views: 456

Answers (6)

patrick
patrick

Reputation: 16949

Figure out if the code is using smart pointers (it probably is), the smart pointers should destroy objects themselves when they go out of scope.

Upvotes: 0

Greg Domjan
Greg Domjan

Reputation: 14095

If you have everything on the stack, or construct elements into containers such as vector then you won't have to worry about memory.

It is however likely you use at least some form of memory allocation (new/malloc/createobject/globalalloc/sysstring/...)

MSVC (COM) ATL provides managing 'RAII' types to help manage lifetime of objects
CComPtr<> will manage scope
CComQIPtr<> will also manage scope, but will also change to the specified type on assignment.

C++ has std::auto_ptr<> which is a bit old and is heading for deprecated boost/tr1 has a bunch of scoped/shared types for managing ptr & arrays - usage depends on if you use new or new[] so that it can call the right delete or delete[]

Upvotes: 3

noisy
noisy

Reputation: 6783

karlphillip give you good advice.

Moreover I want to add, that when you are using objects, best places to delete them is destructor of the class.

you must be careful, because when you delete something twice, your program will blow up.

There is a useful trick to detect whether object was just deleted.

after deleting them, you can set pointer to null

delete foo;
foo=null;

next time you can check whether it is equal to null, and in otherwise delete them. And the best thing... even if you will try delete null pointer, nothing will happens! :)

Upvotes: 2

Lou Franco
Lou Franco

Reputation: 89162

You tagged this COM. If so, you are responsible for calling AddRef() and Release() as appropriate for any COM objects you use. They control the reference-counting features in COM, and are not related to the .NET garbage collector.

For your unmanaged objects, you are responsible for calling delete when you are done with them.

Upvotes: 2

karlphillip
karlphillip

Reputation: 93410

On C++ when you allocate memory manually using the new operator, its your job to release this memory later (when its no longer needed) using the delete operator.

What is the difference between new/delete and malloc/free?

Upvotes: 7

Edward Strange
Edward Strange

Reputation: 40859

None. C++ doesn't have a garbage collector.

Upvotes: 9

Related Questions