a的控制块shared_ptr保持活动,同时存在至少一个weak_ptr存在.如果创建共享指针make_shared,则意味着保持分配对象的整个内存.(对象本身被正确销毁,但由于控件块和对象的内存分配在一个块make_shared中,因此它们只能一起解除分配.)
我的理解是否正确?
看起来这种行为代表了一个问题,例如在着名的"缓存示例"中.对象的内存将永远分配.
这在任何实际情况下都是一个问题吗?应该shared_ptr在这种情况下使用构造函数创建(大对象和意图使用weak_ptrs)?
考虑以下代码:
#include <memory>
#include <iostream>
using namespace std;
struct MySharedStruct
{
int i;
};
void print_value_of_i(weak_ptr<MySharedStruct> weakPtr)
{
if (shared_ptr<MySharedStruct> sp = weakPtr.lock())
{ cout << "Value of i = " << sp->i << endl; }
else
{ cout << "Resource has expired"; }
}
int main()
{
shared_ptr<MySharedStruct> sharedPtr(new MySharedStruct() );
sharedPtr->i = 5;
weak_ptr<MySharedStruct> weakPtr;
weakPtr = sharedPtr;
print_value_of_i(weakPtr);
sharedPtr.reset(new MySharedStruct() ); // <<----- How does weak_ptr know it has expired after this line executes?
sharedPtr->i = 10; …Run Code Online (Sandbox Code Playgroud)