Tuesday, March 1, 2011

Why You Shouldn't Store auto_ptr Objects in STL Containers

Title - Why You Shouldn't Store auto_ptr Objects in STL Containers

Details - copying or assigning one auto_ptr to another makes changes to the original in addition to the expected changes in the copy. To be more specific, the original object transfers ownership of the pointer to the target, thus making the pointer in the original null. Imagine what would happen if you did something like this:


std::vector <auto_ptr <Foo> > vf;/*a vector of auto_ptr's*/
 
// ..fill vf
int g()
{
  std::auto_ptr <Foo> temp=vf[0]; /*vf[0] becomes null*/
}

When temp is initialized, the pointer of vf[0] becomes null. Any attempt to use that element will cause a runtime crash. This situation is likely to occur whenever you copy an element from the container. Remember that even if your code doesn't perform any explicit copy or assignment operations, many algorithms (std::swap(), std::random_shuffle() etc.) create a temporary copy of one or more container elements. Furthermore, certain member functions of the container create a temporary copy of one or more elements, thereby nullifying them. Any subsequent attempt to the container elements is therefore undefined.

Reference –
http://www.devx.com/cplus/Article/16328/0/page/6

 Posted By : Preethymol K. S

No comments:

Post a Comment