Re: problems of storing dynamically created objects in a vector
Jess <wdfcj@hotmail.com> wrote in message...
Hello,
I have a program that stores dynamically created objects into a
vector.
[snip]
Read the other posts first, if you haven't.
Putting it all together (assuming you don't want to use a 'smart pointer',
as Ian mentioned), here's a little demo:
// #includes here
#include<iostream>
#include<vector>
#include <sstream>
std::ostringstream out;
class A7{ public:
A7(){ out<<"A7()"<<std::endl;}
~A7(){ out<<"~A7()"<<std::endl;}
A7( A7 const &){ out<<"A7(const A7&)"<<std::endl;}
// A7& operator=( A7 const &){
// out<<"operator=( A7 const &)"<<std::endl;
// return *this;
// }
};
int main(){ using std::cout; // for NG post
cout<<"\n - A7 test -"<<std::endl;
{
std::vector<A7> svA7( 3 );
out<<"- destructing -"<<std::endl;
}
out<<"-----"<<std::endl;
{
std::vector<A7*> svA7( 3 );
// -- fill it --
for( std::vector<A7*>::iterator i( svA7.begin() );
i != svA7.end(); ++i ){
*i = new A7;
}
out<<"-----"<<std::endl;
// -- clean it out --
for( std::vector<A7*>::iterator i( svA7.begin() );
i != svA7.end(); ++i ){
delete *i;
// *i = 0; // in case it gets called again (if function)
}
}
cout<<out.str()<<std::endl;
out.clear(); out.str("");
cout<<"\n - A7 test - END"<<std::endl;
return 0;
}// main()
[ Why 'out'? Because that's the way I needed to try it in my TestBench pgm,
and I just didn't feel like changing them all back to std::cout. <G> ]
--
Bob R
POVrookie