【发布时间】:2019-11-10 03:44:44
【问题描述】:
有一个资源:“aaa”,他的类型是“AAA”。 “aaa”是由shared_ptr管理的,我们可以通过函数获取它的weak_ptr:
std::weak_ptr<AAA> get_aaa_weakPtr();
现在,client_code 想要访问“aaa”,并将“aaa”转移到它的 child_functions。 就像这样:
void mainFunc(){
std::shared_ptr<AAA> sPtr = get_aaa_weakPtr().lock();
assert( sPtr );
// use sPtr
// ...
childFuncA( /* also_need_aaa */ );
childFuncB( /* also_need_aaa */ );
childFuncC( /* also_need_aaa */ );
}
在 child_functions 中我应该选择哪种参数类型? 弱点?还是 shared_ptr?
【问题讨论】:
-
assert()可能是错误的。 -
@Deduplicator 怎么样:“assert(sPtr!=nullptr);” ?
-
问题在于它看起来很可能指针实际上为为空。
标签: c++11 parameters shared-ptr smart-pointers weak-ptr