All right, you guys were very helpful with my last question, so I'll try another one. This is also homework and while the last one was quite old, this has been submitted and is waiting to be marked. So if there's anything that will bite me it'll probably be this problem. I've obfuscated the class names and such since it's still possible to submit the assignment (for other students).
I have a class whose only member is a pointer to an Object. This class is constructed to expose certain operations from the pointer it is currently holding - the Object *o_
which is a base class to Object{1, 2, 3, ...}
. Now, I'm able to do the following without any memory leaks or crashes.
std::vector<ObjectPtr> v;
v.push_back(ObjectPtr(new Object1(..., ..., ...)));
v.push_back(ObjectPtr(new Object2(..., ...)));
v.push_back(ObjectPtr(new Object1(.., .., ..)));
// Copy Constructor Ptr
std::vector<ObjectPtr> v2(v);
// Assignment Operator Ptr
std::vector<ObjectPtr> v3;
v3 = v2;
All this works, and there are no memory leaks. But if I try to read in the contents from a file with a istream_iterator<ObjectPtr>
it starts to leak. ObjectPtr is the only class handling dynamic memory and the Object *o_
is either set to NULL or allocated by Object{1, 2, 3, ...}
.
The file to be read looks like this
Object1 ... ... Object2 ... ... Object1 ..
std::ifstream is("file.txt");
std::istream_iterator<ObjectPtr> in(is), end;
for (; in != end; ++in)
cout << *in << "\n";
The friend function in ObjectPtr
used to read in these values looks like
friend istream &operator>>(istream &is, ObjectPtr &op) {
std::string tmp;
while (std::getline(is, tmp)) {
if (tmp == "Object1") {
op.o_ = new Object1;
return is >> (Object1 &)*(op.o_); // Send it to operator>> for Object1
}
if (tmp == "Object2") {
op.o_ = new Object2;
return is >> (Object2 &)*(op.o_);
}
...
}
return is;
}
Somewhere here it starts unicorning on me, and I'd really like to know why.
In a nutshell - istream_iterator leaks memory while assignment and copy constructor works properly, which leads me to believe that the classes Object{1, 2, 3, 4, ..}
are constructed correctly, and the problem is to be found within operator>>
.