c++ - static pointer initialization is reset 'after' initialization -
i have 2 classes this:
class basiclogger { //... } class logger { public: static boost::shared_ptr<logger> log_; static basiclogger &log(const std::string &key){ if (!log_) { log_.reset(new logger()); } homecoming (*log_)(key);//calls operator() } virtual basiclogger & operator()(const std::string &key); virtual ~logger(); }; //definition of static fellow member boost::shared_ptr<logger> logger::log_; then somewhere in code utilize above classes :
namespace{ basiclogger & csv = logger::log("trip.csv"); } my problem started when noticed ~logger() never called, started debugging. command first rushed basiclogger & csv = logger::log("trip.csv"); line initialized static shared pointer variable logger::log_
then line boost::shared_ptr<logger> logger::log_; executed reset log_ null !. expect shared pointer logger::log_ go out of acope @ end of application , execute logic invoking ~logger() never called.
am next wrong/bad practice? suggestions?
thanks
you're looking @ static initialization order fiasco (also nice info on https://isocpp.org/wiki/faq/ctors)
the convenient way "fix" to
use function local static instead of globals use file-locals static (inside single translation unit, initialization order defined)so:
static boost::shared_ptr<logger>& getlog() { static boost::shared_ptr<logger> log_; if (!log_) { log_.reset(new logger()); } homecoming log_; }; static basiclogger &log(const std::string &key){ homecoming (*getlog())(key);//calls operator() } see live on coliru
that said, looks might want maintain weak_ptr there.
c++ boost static-members
No comments:
Post a Comment