Re: Useless use of smart pointers
On Jun 4, 2:46 pm, Matthias Kluwe <mkl...@gmail.com> wrote:
Hi!
class Obj;
class ObjStore1 {
public:
const Obj* get( const std::string& filename );
~ObjStore1();
private:
typedef std::map< std::string, const Obj* > store_type;
store_type store;
};
const Obj* ObjStore1::get( const std::string& filename ) {
store_type::const_iterator it = store.find( filename );
if ( it != store.end() ) {
return it->second;
} else {
std::auto_ptr< Obj > pObj( new Obj( filename ) );
store[ filename ] = pObj.get();
return pObj.release();
}
}
In this implementation, ~ObjStore1 needs to delete the Objs:
....
1. One thing worth mentioning explicitly:
the thread is titled "Useless Use of Smart
Pointers", but the auto_ptr is not
useless, it's there for exception safety.
If the insert into the map throws, the
Obj* will get deleted.
2. I agree with Maxim Yegorushkin that the
original implementation is near optimal.
IM-not-so-HO, none of the suggested changes
improves the functionality in the slightest,
they simply obfuscate what the class does.
3. The use of std::string as the map key caught
my eye.
It may not be an issue in the OP's applications,
but in the code I work on, the use of
std::string was a significant source of
inefficiency, to the point that we ended up
replacing it with something else in most
of our code. Even comparisons ended up
being an issue.
Related to that, a question:
Are string comparisons guarranteed
(by the standard) not to throw?
I couldn't find an answer to this in
my copy of Josuttis.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]