TITLE: auto_ptr? use with caution! [ I use auto_ptr. It is a useful class. There are some shortcomings which is why this is a tip. -adc ] SCOTT: bsnyder@aplcenmp.apl.jhu.edu ( Snyder brian scott ) > Hello. I'm curious as I've been going through reading/learning about > exception handling in C++, I've started using the auto_ptr template > class, and > it seems to me, that even if you don't need to use it for 'resource > aquisation' type model, it is still very usefull to gaurantee no memory > leaks, > so is there ever a situation where you wouldn't want to use it, or > should I > say, is there ever a situation where you don't want to use it, over a > regular > pointer to an object? KUEHL: dietmar.kuehl@claas-solutions.de Well, 'auto_ptr' is a strange class. It is extremely useful in some places but quite complicated to use in others. Pitfalls are lurking all over if you start to use it for things it is not intended for. Here are some examples: - 'auto_ptr ap(new int[10]);' will result in "undefined behavior" because the allocated array is released with 'delete' instead of 'delete[]'. Thus, never try to manage the storage for an array with 'auto_ptr'. - 'auto_ptr ap1(new int()); auto_ptr ap2(ap1); return *ap1;' will also result in "undefined behavior" (if I remember FDIS correctly): the pointer, not only ownership like in CD2, is transfered to 'ap2'. - 'vector > vec' (or some other container) is an invitation of trouble: it is not sufficiently specified at all, when objects are copied during 'vector' operations to make sure that not the 'auto_ptr' owning the object is destroyed and thereby releases the corresponding pointer. Instead of using 'auto_ptr' a self-made reference counted class (which can normally be invasive) is preferable. The only real uses of 'auto_ptr' are of the following form: - temporary storing a pointer in a section of code where an exception might be thrown. This normally does not involve passing the pointer around (if it has to be passed around, it should always be passed by reference to make sure that the pointer is not released). - returning an unmanaged pointer from a function and immediately managing the pointer afterwards. Potentially, an 'auto_ptr' may be member of a class which cannot be copied or which has appropriate copy constructor and copy assignment. I normally prefer explicit management of the pointer or a reference counted version. In total, I think that 'auto_ptr' should be used very careful. However, I also think that a program should not use pointers directly to manage objects (pointers are occasionally useful as iterators). But I prefer reference counted pointers.