2015-05-11 54 views
-1

我正在阅读以下评论部分所述的代码片段。当共享指针被破坏?

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

+0

_“为什么'sp'在被评论的地方被摧毁?”_因为它超出了范围。 – Michael

回答

1

我的问题是,两个指针如何指向相同的资源为myClass& obj2 = *sp;

这没有意义。他们大概的意思是:

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

为什么sp是在这个地方,其中被毁作为评论?

这是因为sp在引入嵌套范围构成由

shared_ptr<myClass> sp2; 
{ // This starts a new scope 
    .... 
} // This ends the scope 

在嵌套范围的结束时,所有自动变量破坏。

从标准:

3.7.3自动存储持续时间[basic.stc.auto]

1块范围变量显式声明register或不显式声明staticextern具有自动存储时间。这些实体的存储会持续到创建它们的块退出。

+0

我以为sp'在'}'后被破坏了,为什么在'}'之前呢? – Allanqunzi

+0

@Allanqunzi:你在'}之前“或”之后“的意思是什么?它在程序离开程序块时被破坏,其结尾由'}表示。 –

+0

@Allanqunzi,范围以'}'结束。该标准说明自动变量必须在范围的最后被破坏。范围结束后,对象的生命不存在。见标准3.7.3/1。 –