I am concerned about buffer overflows, and I need to get some characters out of a class that derives from std::istream. From what I understand there is no way to stream to an std::string directly from an istream, without my own >> operator. So I was considering streaming the contents to a char array, then putting that into a std::string. Here is a simple example:
char CharArray[1000] = {0};
SomeIStream >> CharArray;
std::string StuffFromStream(CharArray);
However, there seems to be no way to know that CharArray will not be overflowed. Is there some maximum the stream extraction operator will write to chararray? Is there some way to check how much will be extracted preemptively? Is this just all wrong, Is there some way that is much better than this?
Edit1:, I fixed my not a memory leak. No need to call delete. I can’t believe I did that.
Edit2: The suggestion to use the >> directly to string was suggested. I attempted that previous in the code base this problem came from and it failed. Saying that no suitable match for the operator could be found. I then tried with an std::fstream and it failed again. Trying the std::fstream code in simple minimalistic project succeeded. This tells me that something else is wrong with my larger project. The original intent of this question is no longer valid.
Edit3: I solved this. I was attempted to stream to a typedef String, which I thought was actually and std::string, but it was really a const std::String. Naturally there isn’t a stream extraction operator for writing to an unwritable object, so it just gave me all the operators listed in the istream header (the one I needed was in the string header).
Thanks to the people who pointed out my faulty research and pointe me in the right direction.
If you’ve (properly) inherited from std::istream, then you don’t need to do anything special and can just use
operator >> (std::istream&, std::string&).When I say “properly,” I mean overridden the appropriate virtual functions from istream.
“I know that if there is an exception before the delete this will leak memory.” No it won’t. You didn’t allocate
CharArraywithnew; callingdeleteon it will not do what you want.