architecture - Getting started with smart pointers in C++ -


i have c++ application makes extensively use of pointers maintain quite complex data structures. application performs mathematical simulations on huge data sets (which take several gb of memory), , compiled using microsoft's visual studio 2010.

i reworking important part of application. reduce errors (dangling pointers, memory leaks, ...) want start using smart pointers. sacrificing memory or performance acceptible long limited.

in practice of classes maintained in big pools (one pool per class) , although classes can refer each other, consider pool owner of instances of class. however, if pool decides delete instance, don't want of other classes still refers deleted instance have dangling pointer.

in part keep collection of pointers instances delivered other modules in application. in practice other modules maintain ownership of passed instance, in cases, modules don't want take care of ownership , want pass instance collection, telling "it's yours now, manage it".

what best way start introducing smart pointers? replacing pointers [at random] smart pointers doesn't seem correct way, , doesn't deliver (or of the) advantages of smart pointers. better method?

which types of smart pointers should further investigate? use std::auto_ptr deallocation of locally allocated memory, seems deprected in c++0x. std::unique_ptr better alternative? or should go straight shared pointers or other types of smart pointers?

the question replacing existing raw pointers smart pointers seems similar instead of asking how easy is, asking best approach be, , kind of smart pointers suited best.

thanks in advance ideas , suggestions.

here 3 varieties found in new c++11 standard (unique_ptr replaces auto_ptr)

http://www.stroustrup.com/c++11faq.html#std-unique_ptr

http://www.stroustrup.com/c++11faq.html#std-shared_ptr

http://www.stroustrup.com/c++11faq.html#std-weak_ptr

you can read text each pointer , there explanation of when use in there. local memory management unique_ptr choice. non-copyable movable move around receiver takes ownership of it.

shared_ptr used if want share object instance around no 1 owning object , make sure doesn't deleted while still has reference it. once last user of object destroys shared_ptr container, contained object deleted.

weak_ptr used in conjunction shared_ptr. enables 1 "lock" see if reference shared_ptr object still exists before trying access internal object.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -