-
ostream&
Hi,
I have this following method, wanting to add a string to a std stream
the function toString() returns a pointer to a string. the question is, when I add it to a stream, does it create a copy or add the current pointer, and therefore, what is the correct time to release the allocated memory of this pointer?
I just don't get this whole streaming thing...
Code:
//Edge.h
class Edge
{
char* toString() const;
};
#endif
//EdgeNode.h
class EdgeNode
{
friend std::ostream& operator << (ostream& out,const EdgeNode &eNode);
};
//EdgeNode.cpp
#include EdgeNode.h
ostream& operator << (ostream &out, const EdgeNode &eNode)
{
char *p=eNode.m_edge.toString();
return out << p;
delete [] p;
}
//EdgeList.h
class EdgeList
{
friend std::ostream& operator << (ostream& out,EdgeList eList &);
}
-
The answer to your direct question: When the call to operator<<(ostream &, char *) returns, the char * passed in is no longer needed to produce correct output (a copy is made of the content pointed to by char *, or the data has actually been sent to the output device already.
Would it be difficult to make eNode.m_edge.toString return a std::string, instead of a char pointer? If so, you would avoid the problem of deallocating completely.
Your current code is flawed in that it returns before it deletes p, so it will definitely leak memory.
--
Mats
-
this is a school assignment, a requirement is that the is a method that returns a char*
can i not do somthing like:
Code:
out = out << p;
delete [] p;
return out;
-
Don't need the out = part.
--
Mats
-
so if i have a linkedList
can i do somthing like
Code:
ostream& operator << (ostream& out,const EdgeList & eList)
{
EdgeNode *current=eList->getHead();
while (current!=NULL)
{
out << current << ',';
current=current->getNext();
}
return out;
}
-
That looks like it should be correct, except that getHead() and getNext() should be overloaded such that if the EdgeList object is const, they would return const EdgeNode* instead of EdgeNode*. Then you would change current to be a const EdgeNode*.