C++: RAII with auto_ptr and shared_ptr
May 16, 2008
RAII: Resource Aquisition Is Initialization - The technique combines acquisition and release of resources with initialization and uninitialization of objects.
auto_ptr: is a pointer-like object (a smart pointer), whose destructor automatically calls delete on what it points to. It’s important that there never be more than one aut_ptr pointing to an object because an auto_ptr automatically delete what it points to when the auto_ptr is destroyed.
std::auto_ptr<Student>p1(new Student); //p1 points to an Student object
std::auto_ptr<Student>p2(p1); //p2 now points to the obj, p1 is now null
p1 = p2 //p1 now points to the obj, p2 is null
shared_ptr: is a reference-counting smart pointer that keeps tracks of how many objects point to a particular resource and automatically deletes the resource when nobody is pointing to it any longer. (Like a garbage collection except that such pointers can’t break cycles of references, e.i two otherwise unused objects that point to one another)
std::tr1::shared_ptr<Student>p1(new Student); //p1 points to a Student object
std::tr1::shared_ptr<Student>p2(p1); //both p1 and p2 point to the object
p1 = p2; //same
Both auto_ptr and tr1::shared_ptr use delete in their destructors, not delete[]. Therefore, they should not be used with dynamically allocated arrays:
std::auto_ptr<std::string> aps(new std::string[10]); //bad
std::tr1::shared_ptr<int>spi(new int[1024]); //bad
Leave a Reply