A friend of mine just told me that he too hit the vector trap of my previous post. Instead of reading the STL code he wrote a class with debug output to track down what happens to the objects inside of the several containers.
Yeah! The illumination class. This is what everybody hacks at least once in his C++ live. And here goes mine:
class Illuminate { public: Illuminate() : _id(id++) { cout << "default constructor " << _id << endl; } Illuminate(const Illuminate& rhs) : _id(id++) { cout << "copy constructor " << _id << " <- " << rhs._id << endl; } Illuminate& operator=(const Illuminate& rhs) { cout << "operator=" << _id << " <- " << rhs._id << endl; return *this; } ~Illuminate() { cout << "destructor " << _id << endl; } private: static int id; const int _id; }; int Illuminate::id = 0;
Use it for example like this:
int main() { vector<Illuminate> foo(3); cout << "mark" << endl; }
The program output then shows clearly what I tried to explain in my previous post:
default constructor 0 copy consstructor 1 <- 0 copy consstructor 2 <- 0 copy consstructor 3 <- 0 destructor 0 mark destructor 1 destructor 2 destructor 3
No comments:
Post a Comment