0

I am trying to read a XML file and buffer it in a std::stringstream, but when I call str() function on the buffered data I am getting a bad ptr..

Code...

std::stringstream pushFileToStream(const char* xmlFile)
{
    std::stringstream buffer;

    std::ifstream file(xmlFile);
    if ( file )
    {
        buffer << file.rdbuf();
        file.close();
    }
    return buffer;
}

int main()
{
    const char* xmlFile = "resources/sample.xml";
    std::stringstream inputLicenseFile = pushFileToStream(xmlFile);

    std::string strXml = inputLicenseFile.str();  <--- bad ptr..
    return 0;
}
  • Your code shouldn't compile... streams can not be copied: see e.g. [here](http://stackoverflow.com/questions/6010864/why-copying-stringstream-is-not-allowed). So, how are you getting a runtime error? `.str()` returns a `std::string` not a pointer, so what's all this talk of a "bad pointer"? If this really compiles for you, what compiler and version are you using? It would have to be prehistoric. Anyway, just have `pushFileToStream` accept the stream to operate on by reference, rather than trying to return a stream by value... that's more flexible anyway. – Tony Delroy Nov 25 '14 at 06:25
  • 2
    @TonyD: They can be moved though. And the way he's using it, it should use the move constructor. – Benjamin Lindley Nov 25 '14 at 06:26
  • @TonyD second to what Benjamin said. clang 3.5 has no issues generating the proper move-construction for this. – WhozCraig Nov 25 '14 at 06:27
  • @BenjaminLindley: good point for C++11... seems to be missing from GCC on ideone - even with an explicit `return std::move(buffer);` it doesn't consider any move constructor.... – Tony Delroy Nov 25 '14 at 06:31
  • If you are trying to read a file, this is how you do without unnecessary copying: http://stackoverflow.com/a/10336701/412080 – Maxim Egorushkin Nov 25 '14 at 09:54
  • @TonyD: I'd suspect that's because their lib was missing the move ctor for `stringstream`. That's not fixable with `move`. – MSalters Nov 25 '14 at 09:54

0 Answers0