全局变量没有增加(是gcc坚果吗?)

时间:2014-06-18 10:19:17

标签: c++ c++11 shared-ptr

我有以下愚蠢的代码: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

1 个答案:

答案 0 :(得分:5)

A打印到global后,删除cout个对象。