我有以下愚蠢的代码:IDEONE
有人可以解释,为什么在删除std :: vector中的对象A时全局计数器不会增加hack
#include <iostream>
#include <memory>
#include <vector>
int global;
class A {
public:
A(int i): a(i) {}
~A() {
std::cout << "delete A" << std::endl;
++global;
};
int foo() {
return a;
}
int a;
};
int main() {
int c = 0;
int loops = 10;
global = 0;
// Make vector of pointers
std::vector<std::shared_ptr<A> > vec;
for(int i = 0; i< 10; i++) {
vec.push_back( std::shared_ptr<A>(new A(i)) );
}
for(int i=0; i<loops; i++) {
for(auto & p : vec) {
c += p->foo();
}
}
std::cout << " deleted:" << global << std::endl;
}
输出:
deleted:0
delete A
delete A
答案 0 :(得分:5)
将A
打印到global
后,删除cout
个对象。