Template Specialization auto_ptr <T>
Maybe I'm too weird, but then again, I'm kind of like clean interfaces. Let me say that I want the specialization auto_ptr for fstream - I need a standard default thread for the general case, but allow pointer replacement?
template <>
class auto_ptr<fstream> {
static fstream myfStream;
fstream* ptr;
public:
auto_ptr() {
// set ptr to &myfStream;
}
reset(fstream* newPtr) {
// free old ptr if not the static one.
ptr = newPtr
};
}
Do you find something else or more elegant? And how would you save something similar to the above from distributing outside this particular compilation unit?
[Actual template is boost :: scoped_ptr.]
EDIT:
This is a contrived example. Ignore fstream - this is about providing a default object instance for auto_ptr. Perhaps I do not want to provide a specialized instance, but would like to keep the auto_ptr semantics for this static object by default.
class UserClass {
public:
auto_ptr<fstream> ptr;
UserClass() { }
}
. , . , , , ?
-, , , .
Boost auto_ptr. - , .
, factory .
EDIT: auto_ptr - , :
tempate < class T, T *d >
struct defaulted_auto_ptr
: public auto_ptr< T > {
defaulted_auto_ptr( T *p = d ) throw() : auto_ptr<T>( p ) {} // set default
defaulted_auto_ptr( auto_ptr<T> &r ) throw()
: auto_ptr<T>( r ) {} // allow conversion
template< class O > defaulted_auto_ptr( auto_ptr<O> &r ) throw()
: auto_ptr<T>( r ) {}
};
fstream default_file;
typedef defaulted_auto_ptr< fstream, &default_file > file_ptr;
auto_ptr< fstream > baseptr = file_ptr(); // can assign to auto_ptr, but unsafe
I have little doubt about the trade-off between costs and benefits, but this is better than redefining completely auto_ptr.
You still need to figure out what to do if the destroyed object is destroyed. default_filehigher will be deleted, potentially many times.