Queue und pop()
-
Hallo!
Wie bekomme ich meinen Pointer zurück?

queue <char *, deque<char *> > m_pqNettoMsgs ;
char *pac = new char[6];
strcpy( pac, "Hallo");
m_pqNettoMsgs.push( pac);
pac = m_pqNettoMsgs.pop() ; // line 28
delete [] pac;
[C++ Error] Unit1.cpp(28): E2109 Not an allowed type
-
Benutze Borland C++ Builder 5 .
-
pop() hat keinen Rückgabewert. Benutze back() dafür. back() liefert eine Referenz, die nach pop() aber ungültig wird. D.h. back() aufrufen, Kopie machen, pop() aufrufen.
queue <char *, deque<char *> > m_pqNettoMsgs ; char *pac = new char[6]; strcpy( pac, "Hallo"); m_pqNettoMsgs.push( pac); pac = m_pqNettoMsgs.back(); m_pqNettoMsgs.pop(); delete [] pac;
-
Danke, funktioniert. Ich nehme allerdings front(), da ich ja einen FIFO implementieren will.
Dann frage ich mich allerdings, warum ich nicht einfach einen vector benutzte. Der Arbeitsaufwand ist ja wohl der gleiche. Ich hatte eigentlich gedacht, dass ich mir durch die Verwendung von queue einen Schritt spare.
Naja, wieder was gelernt.

-
Öhm jo front() ist wohl das was du willst. Hab ich jetzt nicht drauf geachtet, aber es geht auch ums Prinzip bei dieser Art von Operationen.
Hier ein Auszug aus der SGI STL Doku zu front(). Dieses Design wirst Du übrigens in allen Containerklassen finden:
[3] One might wonder why pop() returns void, instead of value_type. That is, why must one use front() and pop() to examine and remove the element at the front of the queue, instead of combining the two in a single member function? In fact, there is a good reason for this design. If pop() returned the front element, it would have to return by value rather than by reference: return by reference would create a dangling pointer. Return by value, however, is inefficient: it involves at least one redundant copy constructor call. Since it is impossible for pop() to return a value in such a way as to be both efficient and correct, it is more sensible for it to return no value at all and to require clients to use front() to inspect the value at the front of the queue.