Difficulty returning junks in my C++ stack implementation -


i have implemented stack in c++, have problem returning junks. example, have:

...  template<class t> t stack<t>::pop() {     /* verific dacă există elemente pe stivă */     if( isempty() )     {         t junk;         fprintf(stderr, "no data.\n");         return junk;     }      ...  } 

this not right way solving problem, because have valgrind error. how can solve it?

this poor idea because (among other things) if t's copy constructor can throw, can destroy data (removes item stack, copying return item throws, destroys copy).

one way fix problem change interface this:

void stack<t>::pop(t &ret) {      if (!isempty())         ret = data[top--]; } 

or, provide indication of whether succeeded:

bool stack<t>::pop(t &ret) {      if (isempty())         return false;     ret = data[top];     --top;     return true; } 

this way, if copy constructor throws, top never decremented, item remains on stack. if execution gets past that, rest of function can't throw, either succeed (the item copied proper destination , removed stack) or else function has no effect @ (the item remains on stack).


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

datatable - Matlab struct computations -