gpt4 book ai didi

c++ - 全局变量不递增(gcc 疯了吗?)

转载 作者:太空宇宙 更新时间:2023-11-04 16:14:37 24 4
gpt4 key购买 nike

<分区>

我有以下愚蠢的代码:IDEONE

有人可以解释一下,为什么在删除 std::vector 中的对象 A 时,全局计数器不会增加???

#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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com