Search code examples
c++asynchronousargument-passinglifetime

Argument lifetime of an asynchronous function call


Herb Sutter in GotW #91 Solution: Smart Pointer Parameters states " Thanks to structured lifetimes, the called function’s lifetime is a strict subset of the calling function’s call expression." Does this apply to asynchronous function calls?

void myFunc(Bar * arg);
...
auto bar = new Bar;
std::thread t1(myFunc,bar);
delete bar;
join t1;

I presume that in this case, deleting bar could invalidate the argument passed into myFunc on thread t1.


Solution

  • 1) Here you're passing a pointer into the ctor of t1 so all the structured lieftime related statements only apply to the pointer rather than the object it points to.

    2) There are no asynchronous function calls here - you're calling a std::thread ctor and all structured lifetime statements apply to the ctor only rather than its side effects that eventually will make a call to myFunc.