Re: problems of storing dynamically created objects in a vector
On Jun 10, 1:56 pm, Jess <w...@hotmail.com> wrote:
On Jun 10, 3:43 pm, "BobR" <removeBadB...@worldnet.att.net> wrote:
Jess <w...@hotmail.com> wrote in message...
[Code severely cut...]
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;
}
return 0;
}// main()
Thanks! I've run the example on my computer and here's what I've got:
- A7 test -
A7()
A7(const A7&)
A7(const A7&)
A7(const A7&)
~A7()
- destructing -
Where does the first A() come from?
What's the second argument to the constructor of the vector in
svA7?
The STL has been designed to work with classes without default
constructors, so it never uses a default constructor internally,
only the copy constructor or assignment.
I guess when the vector of three A7 objects is constructed
perhaps one A7 object is created first and then copy
constructor is called three times to copy the initial object
to the vector.
It's required, because the constructor is actually:
vector<T>::vector( size_type n, T const& = T() ) ;
Try replacing the default constructor with one which requires an
argument (say an int). You can still write:
vector< A7 > svA7( 3, A7( 0 ) ) ;
for example.
Then the first ~A() means the initial A7 object is
destroyed?
The first ~A() is the destructor of the temporary object which
was passed as the second argument to the constructor of vector.
When is it destroyed?
As soon as we return from the constructor of vector.
Furthermore, does a vector always create an initial object and
then destroy with the vector finishes with it?
The vector doesn't. You must always supply it with an object
(or objects) to be copied, if the vector is not empty.
I think this is what Ian meant? Is there any way that the
compiler doesn't create a temporary object?
The standard requires it. I don't think that there's anyway you
(or the compiler) can avoid it.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34