mercredi 5 avril 2017

How to keep alife a shared_ptr-object of which members are used in an asynchronous function?

Imagine the following code:

{
  auto o = std::make_shared<O>();
  async(&o->member, [] { do_something_else(); } );
}

async will, for example, start a thread using member of o which was passed as a pointer. But written like this when o is going out of scope right after async() has been called and it will be deleted and so will member.

How to solve this correctly and nicely(!) ?

Apparently one solution is to pass o to the capture list. Captures are guaranteed to not be optimized out even if not used. However, recent compilers (clang-5.0) include the -Wunused-lambda-capture in the -Wextra collection. And this case produces the unused-lambda-capture warning.

I added (void) o; inside the lamdba which silences this warning.

Is there are more elegant way to solve this problem?

(The origin of this problem is derived from using write_async of boost::asio)

Aucun commentaire:

Enregistrer un commentaire