Re: new to vectors, problems
Quote:
Originally Posted by paradoxresolved
Hi all,
I'm experimenting with vectors and trying to accomplish some basic things:
1) trying to figure out whether or not "new" objects are deleted when the vector is destroyed or cleared.
No. The vector has no idea that the objects being placed in it were created with operator new by you. Therefore it cannot call "delete". The basic rule is that if you call "new" or "new[]", then you have to call "delete" or "delete[]".
Second, I looked at your code. To make it easier, create a default constructor so that you can store objects, not pointers. Your current code has a memory leak, since you never called "delete" on those objects. Instead, you could just have done this:
Third, do not call your variable "list". There is already a std::list class for C++, and your code will cause confusion, and in some cases, compiler errors.
Fourth, why are you testing your program's output by doing something like writing to a file? Why not just do a simple "cout" to test things? Right now, you don't know if the problem is caused by vector, or you not doing the output correctly.
Fifth, a std::vector is non-POD (Plain-Old-Data). You cannot use functions such as iostream::write() to output the vector's contents, or read() to read in values. This is C++, not 'C'. To input/output values of non-POD classes, you must do something called serialization. The easiest form of this is to write out or read in the values one-by-one in a loop.
In general, functions that act on raw memory blocks, i.e. memset(), memcpy(), malloc(), fwrite(), etc. cannot be used on non-POD C++ classes and structs. They do work on POD (C-compatible) structures, i.e. structs or classes that contain only ints, doubles, chars, arrays, etc. Read up on the many threads that discuss this here.
Here is a rewrite of your code:
Code:
#include <vector>
#include <iostream>
#include <fstream>
class MyClass
{
public:
MyClass(int value = 0);
int Value;
};
MyClass::MyClass(int value) : Value(value)
{ }
using namespace std;
int main()
{
int i = 0;
vector<MyClass> Mylist;
for( i = 0 ; i < 5 ; i++)
Mylist.push_back( MyClass(i));
ofstream out("C:/TempFile", ios::out | ios::binary );
if(!out)
{
cout << "Cannot open output file.\n";
return 1;
}
// This is totally wrong!
// out.write((char*) &list, sizeof(class vector<MyClass>));
for (int i = 0; i < Mylist.size(); ++i )
{
out << Mylist[i].Value << "\n";
cout << Mylist[i].Value << "\n";
}
Mylist.clear();
int size = Mylist.size();
for( i = 0 ; i < size ; i++ )
{
cout << Mylist[i].Value << endl;
}
}
I didn't do the reading in, since that is wrong also, similar to the way you were doing the output. Hopefully you see how to fix it.
Regards,
Paul McKenzie