我正在阅读以下评论部分所述的代码片段。当共享指针被破坏?
#include <memory>
struct myClass {
~myClass() {
cout << "dtor" << endl;
}
};
void myFunc() {
shared_ptr<myClass> sp2;
{
shared_ptr<myClass> sp(new myClass);
myClass& obj = *sp;
sp2 = sp; // OK, resource shared
myClass& obj2 = *sp; // OK, both pointers point to same resource
// sp destroyed here, yet no freeing: sp2 still alive
}
cout << "out of inner block" << endl;
// sp2 destroyed here, reference count goes to 0, memory is freed
}
我的问题是,为什么两个指针指向相同的资源为myClass& obj2 = *sp;
?为什么sp
在我们达到评论// sp2 destroyed here, reference count goes to 0, memory is freed
的地方被摧毁?
_“为什么'sp'在被评论的地方被摧毁?”_因为它超出了范围。 – Michael