开发者

Unmanaged C++ Garbage Collection help

I'm a .net programmer, without much experience with 开发者_如何学Pythonunmanaged 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


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


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?


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[]


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.


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! :)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜