OT: Hello, Happy new year and a Question.

Carlos Eduardo de Brito Novaes carlosnov@gmail.com
Sat Dec 31 16:28:00 GMT 2005


	Hello to everyone, and happy new year.
	
	This is my first post to this list, and I am not very sure if this is the 
correct place to post my question. Anyway..

	I am starting to program using STL and found something strange in the 
vector<> implementation. Every time I call push_back to add a new object, the 
container call the destructor for the previous (if any) object.
	I had make this code to test and comprove:

****** CODE ******
#include <iostream>
#include <vector>
using namespace std;
class Dummy {
public:
  Dummy(int value){
    mValue = value;
    cout << "Dummy value " << mValue << " created at address:   " << (int) 
this << endl;
};
  ~Dummy(){
    cout << "Dummy value " << mValue << " deleted from address: " << (int) 
this << endl;
};
  void Set(int value){
    mValue = value;
    cout << "Dummy value " << mValue << " set in address:       " << (int) 
this << endl;
};
private:
  int		mValue;
};

main(){
  vector<Dummy>	MyVector;
  Dummy			MyDummy(0);
  int x;
  for (x=0; x<5; x++){
    MyDummy.Set(x);	
    cout << "Push Back..." << endl;
    MyVector.push_back(MyDummy);
  }
cout << "This is the End" << endl;
};
****** END OF CODE ******

when i run this piece, i got:
****** CONSOLE OUTPUT *******
Dummy value 0 created at address:   -1073744480		(this is OK)
Dummy value 0 set in address:       -1073744480			(OK)
Push Back...
Dummy value 1 set in address:       -1073744480			(OK)
Push Back...
Dummy value 0 deleted from address: 134524936			(I cant understand why this)
Dummy value 2 set in address:       -1073744480
Push Back...
Dummy value 0 deleted from address: 134524944
Dummy value 1 deleted from address: 134524948
Dummy value 3 set in address:       -1073744480
Push Back...
Dummy value 4 set in address:       -1073744480
Push Back...
Dummy value 0 deleted from address: 134525096
Dummy value 1 deleted from address: 134525100
Dummy value 2 deleted from address: 134525104
Dummy value 3 deleted from address: 134525108
This is the End
Dummy value 4 deleted from address: -1073744480
Dummy value 0 deleted from address: 134525264
Dummy value 1 deleted from address: 134525268
Dummy value 2 deleted from address: 134525272
Dummy value 3 deleted from address: 134525276
Dummy value 4 deleted from address: 134525280
****** END OF CONSOLE OUTPUT *******

	I think that the destructor ~Dummy() should be used to clean up some stuff in 
the class before deleting all pointers. So I cant understand why it gets 
called for the previous last item when i call push_back.
	I had compiled the above code with gcc 3.4 and 3.3, and get the same results, 
so I wonder if is my fault. 

	I ask to someone tell me what i am doing wrong, or point me to some solution.

Thanks in advice.



More information about the Gcc-help mailing list