Based on what I understand, resize
method of the template class vector<class>
uses the constructor without parameters to a create a new object, and then, uses copy constructor to clone the previous object. Indeed, this code prove it:
#include <iostream>
#include <vector>
using namespace std;
class A{
public:
A(){
cout << "Appel constructeur !" << endl;
cout << this << endl;
}
A(const A &a){
cout << "Appel constructeur de recopie" << endl;
cout << this << endl;
}
~A(){
cout << "Appel destructeur !" << endl;
}
};
int main() {
vector<A> t;
t.resize(2);
cout << t.size() << endl;
cout << &t[0] << endl;
cout << &t[1] << endl;
}
The output is with mingw32-g++.exe
:
Appel constructeur !
0x69fedf
Appel constructeur de recopie
0x905690
Appel constructeur de recopie
0x905691
Appel destructeur !
2
0x905690
0x905691
Appel destructeur !
Appel destructeur !
The output with g++
(it calls the constructor twice)
Appel constructeur !
0x55c91bff3e70
Appel constructeur !
0x55c91bff3e71
2
0x55c91bff3e70
0x55c91bff3e71
Appel destructeur !
Appel destructeur !
So my questions are: why create a new object then destroy it? why the first object created has an address very far from the other objects?