Suppose the following code:
void SomeClass::SomeMethod()
{
CComPtr<ISomeService> service = GetService();
ExecuteInNewThread([&]()
{
service->AnotherMethod();
});
}
The function ExecuteInNewThread executes function object in new thread thus the lambda function may be executed after the service pointer will be released.
What would be the best way to prevent this? Doing AddRef() in SomeMethod and Release() at the end of the lambda looks ugly.
Just capture the variable by value and let the copy constructor and destructor worry about ownership semantics- that’s what smart pointers are for. The existing code is most assuredly incorrect.