I was unsure about whether STL containers are entirely copied when passed. First, it worked (so the “fluttershy” element didn’t get added, that was good). Then I wanted to track the construction and destruction of entries….
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
int nextid = 0;
class Entry {
public:
string data;
int myid;
Entry(string in) {
data = in;
myid = nextid;
nextid++;
printf("Entry%02d\n", myid);
}
~Entry() { printf("~Entry%02d\n", myid); }
};
class Meep {
public:
vector<Entry> stuff;
};
void think(Meep m) {
m.stuff.push_back(Entry(string("fluttershy")));
}
int main() {
Meep a;
a.stuff.push_back(Entry(string("applejack")));
think(a);
vector<Entry>::iterator it;
int i = 0;
for (it=a.stuff.begin(); it!=a.stuff.end(); it++) {
printf("a.stuff[%d] = %s\n", i, (*it).data.c_str());
i++;
}
return 0;
}
Produces the following unexpected output( http://ideone.com/FK2Pbp ):
Entry00
~Entry00
Entry01
~Entry00
~Entry01
~Entry00
~Entry01
a.stuff[0] = applejack
~Entry00
That a has only one element is expected, that is not the question. What seriously confuses me is how can one entry be destructed several times ?
What you’re seeing is the destruction of temporary instances.
This line creates a temporary instance which is then copied to another new instance in the container. Then the temporary is destroyed. The instance in the container is destroyed when the entry is removed or the container is destroyed.