[Solved] Why vector not free objects or what happens anyway? [closed]


Annotate your class a little more, and that should make clear what is happening.

#include <vector>
#include <cstdio>

using std::printf;
using std::vector;

class cVtst {
  static int seqCounter;
  int seq;
  int v;
public:
  cVtst(int v) {
    this->v = v;
    this->seq = ++seqCounter;
    printf("Creating cVtst#%d %d\n", seq, v);
  }
  ~cVtst() {
    printf("Closing cVtst#%d %d\n", seq, v);
  }
  cVtst() {
    this->v = ~0 & (~0U >> 1);
    this->seq = ++seqCounter;
    printf("Default Creating cVtst#%d %d\n", seq, v);
  }
  cVtst(cVtst const& other) {
    this->v = other.v;
    this->seq = ++seqCounter;
    printf("Copy Creating cVtst#%d %d\n", seq, v);
  }
};

int cVtst::seqCounter = 0;

int main() {
  vector<cVtst> vc;
  vc.push_back(34);
  vc.push_back(2);
  vc.push_back(-5);
  while (!vc.empty()) vc.pop_back();
}

UPDATE:
What your original example isn’t taking into account is that the C++ compiler will synthesize a copy constructor and a default constructor.

So your output is not showing those constructors, which is why you are seeing an unbalanced set of Creating and Closing output. (I assume that your “So…?” question is “Why are they Creating and Closing output unbalanced?”)

2

solved Why vector not free objects or what happens anyway? [closed]