Hi all,
Conceivably, when testing C++ code that writes a lot to an output file, using std::ostringstream instead of std:ofstream makes for a very handy spy.
The idea is that the object in question accepts a std::ostream in its constructor. The production code then passes either std::ofstream or std::cout, which works fine.
The test passes std::ostringstream, which would be fine, except that it leaks memory. Common lore on the Web has it that std:ostringstream never leaks memory.... but there it is. A simple test case:
#include "TestHarness.h"
#include <sstream>
class MyClass {
public:
MyClass(std::ostream& o) : o_(o) {}
void doStuff() {
o_ << "stuffystuffstuffstuffydistuff";
}
private:
std::ostream& o_;
};
TEST_GROUP(leak_test) {
std::ostringstream o;
MyClass* m;
void setup() {
m = new MyClass(o);
m->doStuff();
}
void teardown() {
delete m;
}
};
TEST(leak_test, leak) {
STRCMP_CONTAINS("stuffy", o.str().c_str() );
}
This will yield the following output:
error: Failure in TEST(leak_test, leak)
Memory leak(s) found.
Leak size: 525 Allocated at: <unknown> and line: 0. Type: "new" Content: "☺"
Total number of leaks: 1
.
It would be nice to have a way to properly dispose of the internal buffer. N.B. memory only leaks if the buffer is actually written to.
Robert