Search code examples
c#javac++managedauto-ptr

How does c++ auto_ptr relate to managed pointers (Java, C#...)


I come from a managed world and c++ automatic memory management is quite unclear to me

If I understand correctly, I encapsulate a pointer within a stack object and when auto_ptr becomes out of scope, it automatically calls delete on the pointed object?

What kind of usage should I make of it and how should I naturally avoid inherent c++ problems?


Solution

  • auto_ptr is the simplest implementation of RAII in C++. Your understanding is correct, whenever its destructor is called, the underlying pointer gets deleted.

    This is a one step up from C where you don't have destructors and any meaningful RAII is impossible.

    A next step up towards automagic memory management is shared_ptr. It uses reference counting to keep track of whether or not the object is alive. This allows the programmer to create the objects a bit more freely, but still not as powerful as the garbage collection in Java and C#. One example where this method fails is circular references. If A has a ref counted pointer to B and B has a ref counted pointer to A, they will never get destructed, even though no other object is using either.

    Modern object orianted languages use some sort of variation of mark and sweep. This technique allows managing circular references and is reliable enough for most programming tasks.