共享指针何时被销毁?

when the shared pointers gets destroyed?

我正在阅读评论中解释的以下代码。

#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 的地方被销毁了?

My question is that how come both pointers point to same resource for myClass& obj2 = *sp;?

这没有道理。他们的意思可能是:

myClass& obj2 = *sp2; // OK, both pointers point to same resource
                 ^^^ sp2, not sp

And why sp is destroyed at the the place where as commented?

那是因为 sp 是在

引入的嵌套作用域中构建的
shared_ptr<myClass> sp2;
{  // This starts a new scope
  ....
} // This ends the scope

在嵌套作用域结束时,所有自动变量都被析构。

来自标准:

3.7.3 Automatic storage duration [basic.stc.auto]

1 Block-scope variables explicitly declared register or not explicitly declared static or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.