
I'm working on making a factory class but have run into a problem. I think I'm trying to get the shared pointer out the wrong way. std::map<std::string, boost::shared_ptr<Logger> > LoggerFactory::loggers; boost::shared_ptr<Logger> LoggerFactory::getInstance(std::string& logger) { boost::shared_ptr<Logger> TheLogger; LoggerMap::iterator i = loggers.find(logger); if (!(*i).second.get()) { TheLogger.reset(new Logger()); loggers[logger] = TheLogger; } else { TheLogger = (*i).second; } return TheLogger; } I thought that the TheLogger = (*i).second line was the correct way to get any logger within the map but when I run it I get this segfault: Program received signal SIGSEGV, Segmentation fault. LoggerFactory::getInstance(std::string&) (logger=@0x22ff58) at e:/boost-1.30.2/boost/detail/shared_count.hpp:123 123 if(use_count_ == 0 && weak_count_ != 0) boost::throw_exception(boost::bad_weak_ptr()); if I comment out the 'TheLogger = (*i).second;' line everything seems to fine. Any ideas? Joshua.

On Sat, 07 Feb 2004 23:12:58 -0600, Joshua Little wrote
LoggerMap::iterator i = loggers.find(logger); if (!(*i).second.get()) {
If logger doesn't already exist in loggers, then i will be loggers.end(). Dereferencing end() is undefined. Use this for your conditional instead: if(i != loggers.end()) Or, if you want to gain speed, do this: boost::shared_ptr<Logger> LoggerFactory::getInstance(std::string& logger) { boost::shared_ptr<Logger>& TheLoggerRef = loggers[logger]; if(!TheLoggerRef.get()) TheLoggerRef.reset(new Logger()); return TheLoggerRef; } This version searches the map only once. find() doesn't add entries, but the array operator does. Todd

todd wrote:
On Sat, 07 Feb 2004 23:12:58 -0600, Joshua Little wrote
LoggerMap::iterator i = loggers.find(logger); if (!(*i).second.get()) {
If logger doesn't already exist in loggers, then i will be loggers.end(). Dereferencing end() is undefined. Use this for your conditional instead:
if(i != loggers.end())
Or, if you want to gain speed, do this:
boost::shared_ptr<Logger> LoggerFactory::getInstance(std::string& logger) { boost::shared_ptr<Logger>& TheLoggerRef = loggers[logger]; if(!TheLoggerRef.get()) TheLoggerRef.reset(new Logger()); return TheLoggerRef; }
This version searches the map only once.
find() doesn't add entries, but the array operator does.
Todd
Thanks Todd, now that I see what I did wrong I wonder why I didn't see it in the first place :) Joshua.
participants (2)
-
Joshua Little
-
todd