c++ - Create a struct instance only if conditions are met in its constructor -
i want create instance of struct if conditions inside constructors met. if conditions not met, want not create instance. not sure if possible, , if not alternate way of doing it?
class consumer { struct samplestruct { myclass * m_object; routingitem() { m_object = null; } myclass(std::string name) { if (! objsetting()->getobj(name, m_object))//this function supposed populate m_object, if fails, dont want create instance return; //i dont want create object if getobj() returns false } }; std::vector<samplestruct> m_arrsample; void loadsettings(std::string name) { samplestruct * ptrs; samplestruct s(name); //i tried following 2 lines did'nt work. looks returning struct constructor still creates instance ptrs = &s; if (!ptrs) return; m_arrsample.push_back(s);//only insert in vector if samplestruct created } }
either use exception (as stefano says), or factory function (as minicaptain says).
the 2 versions this:
#include <stdexcept> #include <memory> struct exceptionstyle { std::unique_ptr<int> m_object; exceptionstyle(std::string const &name) { if (name == "good") m_object.reset( new int(42) ); else throw std::runtime_error(name); } }; void save(exceptionstyle*) {} // stick in vector or class factorystyle { std::unique_ptr<int> m_object; factorystyle() : m_object(new int(42)) {} public: static std::unique_ptr<factorystyle> create(std::string const &name) { std::unique_ptr<factorystyle> obj; if (name == "good") obj.reset( new factorystyle ); return obj; } }; void save(std::unique_ptr<factorystyle>) {} // stick in vector or
can used follows:
void loadsettings(std::string const &name) { // use exception style try { exceptionstyle *es = new exceptionstyle(name); // if reach here, created ok save(es); } catch (std::runtime_exception) {} // use factory style std::unique_ptr<factorystyle> fs = factorystyle::create(name); if (fs) { // if reach here, created ok save(fs); } }
an exception only way transfer control out of constructor without constructing instance. so, alternative check condition first.
Comments
Post a Comment