C++ initialization of local/global object -


i've encountered many time case when there's class, e.g. logfile, has no default constructor, while want initialize instance of it, not on heap.

here example:

logfile logfile;  void init(const std::string& path) {     logfile = logfile(path); } 

the above code not compile, since logfile class has no default constructor.

there few workarounds use:

1. persisting not make heap calls manually, storing object in list (the list sure use heap, won't care it)

std::list<logfile> logfile_holder;  void init(const std::string& path) {     logfile_holder.push_back(logfile(path)); } 

2. using heap, shared pointer/unique pointer:

std::shared_ptr<logfile> logfile_ptr;  void init(const std::string& path) {     logfile_ptr.reset(new logfile(path)); } 

i there more standard solution doing such things?

even looks list workaround, template class designated purpose, without overhead of list, nice.

you use indirection. use global pointer, , initialize function local static:

logfile* logfile_ptr;  void init(const std::string& path) {     static logfile logfile(path);     logfile_ptr = &logfile; } 

for suggestions, there little point in using list (or other data structure) when use smart pointer if use heap.

do note in design based on yours, need pay attention not use global logfile until has been initialized. if unsure, easy check if pointer null.

a simpler approach add default constructor. allow changing behaviour of logfile if used before path set. example, terminate program , describe error, or silently ignore such bugs if don't care premature logging goes missing. or store logging buffer , flush path initialized.


Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -