为什么矢量不是自由物体或者无论如何会发生什么

时间:2017-11-08 16:14:10

标签: c++ vector

我不明白这里发生了什么!我定义了类cVtst,并创建了vector。我会在创建和销毁对象时观察。

class cVtst { 
public: 
    int v;
    cVtst(int v) { 
        this->v = v; 
        printf("Creating cVtst %d\n", v); 
    }
    ~cVtst() { 
        printf("Closing cVtst %d\n", v);
    } 
};

std::vector<cVtst> vc;
vc.push_back(34); 
vc.push_back(2); 
vc.push_back(-5);
while (!vc.empty()) vc.pop_back();

结果是:

Creating cVtst 34
Closing cVtst 34
Creating cVtst 2
Closing cVtst 34
Closing cVtst 2
Creating cVtst -5
Closing cVtst 34
Closing cVtst 2
Closing cVtst -5
Closing cVtst -5
Closing cVtst 2
Closing cVtst 34

所以...?

1 个答案:

答案 0 :(得分:2)

再多注释你的课程,这应该清楚说明发生了什么。

#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();
}

更新: 您的原始示例未考虑的是C ++编译器将合成复制构造函数和默认构造函数。

所以你的输出没有显示那些构造函数,这就是你看到一组不平衡的创建和关闭输出的原因。 (我假设你的&#34;所以...?&#34;问题是&#34;他们为什么创建和关闭输出不平衡?&#34;)