c++ - Output parameter in factory method -


i have class myclass that, often, created parsing string. cannot trust string correct , therefore not want put parsing in constructor. hence, have created static parsing function returns true if string valid , false if invalid. see below:

class myclass { private:     type1 m_membera;     type2 m_memberb;  public:             myclass(const type1& parametera, const type2& parameterb)          : m_membera(parametera), m_memberb(paramterb)      static bool parse(const std::string& input, myclass * result)     {         type1 parama;         type2 paramb;          //parse input , values parama , paramb.         //return false if input invalid.          myclass temp(parama, paramb)         *result = temp;         return true;     } } 

my intent use follows:

void myfunction(const std::string& input) {      myclass * myobject = null;      if(myclass::parse(input, myobject))      {           //use myobject      }      else      {           //log invalid input string      } } 

now, crashes @ run time. , figured because trying de-reference null-pointer, doesn't work. how can fix this?

you need pass either pointer-to-pointer function or pointer reference , allocate new:

static bool parse(const std::string& input, myclass *& result)     {         // ......          result = new myclass(parama, paramb)         return true;     } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -