c++ - When to replace a global std::unique_ptr with a singleton -


a colleague has insisted on using meyer's singleton global pointer variables "there's no guarantee construction of global unique_ptr won't throw". instead of:

#include <memory>  std::unique_ptr<foo> ptr(nullptr); // apparently isn't safe.  int main(/*blah*/) {     ptr.reset(new foo()); } 

we have

unique_ptr<foo> singleton {      try      {          static unique_ptr<foo> ptr();          return ptr;      }      catch (...)      {          std::cerr << "failed create single instance\n";          exit(1);      }      return unique_ptr<type>();  }  int main() { } 

to me seems solution looking problem. have point?

your colleague incorrect (or perhaps out of date, pre-standard versions of unique_ptr might different). nullptr_t constructor of unique_ptr guaranteed not throw (20.7.1.2):

constexpr unique_ptr (nullptr_t) noexcept : unique_ptr() {} 

since it's constexpr (and since nullptr constant expression), required initialized during constant initialization (3.6.2/2). controlling initialization order (the other reason meyers singleton might useful) doesn't apply here.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -