1

There is a resource: "aaa", who's type is "AAA". "aaa" is managed by shared_ptr, and we can get it's weak_ptr by function:

std::weak_ptr<AAA> get_aaa_weakPtr();

Now, the client_code want to visit "aaa", and transfer "aaa" to it's child_functions. Just like this:

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 */ );
}

which kind of parameter type should I choose in child_functions? weak_ptr? or shared_ptr?

hanjie zou
  • 11
  • 2

1 Answers1

0

In case of concurrent programming, i.e. childFuncX can be async, you should pass a weak_ptr and, inside the function, check for the validity of the pointer (with weak_ptr::lock()) and ensure single access to the resource with a std::lock_guard of a mutex, which in you case can be instantiated directly in the main function (or unique_lock as your needs). Avoid global and static to avoid future issues as software evolve over time.

fiorentinoing
  • 948
  • 12
  • 20