【问题标题】:If I want to transfer a resource, which kind of parameter type should I choose? weak_ptr? or shared_ptr如果我想转移一个资源,我应该选择哪种参数类型?弱点?或 shared_ptr
【发布时间】: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


【解决方案1】:

在并发编程的情况下,即 childFuncX 可以是异步的,您应该传递一个weak_ptr,并在函数内部检查指针的有效性(使用weak_ptr::lock())并确保对资源的单一访问互斥锁的 std::lock_guard ,在您的情况下可以直接在主函数中实例化(或根据您的需要 unique_lock )。避免全局和静态,以避免随着软件随着时间的推移而出现问题。

【讨论】:

  • 非常感谢您的建议。我认为weak_ptr是可靠的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-03
  • 2019-06-01
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多