In itself the code posted by you seems ok and innocent, however a std::vector
of char*
made me suspicious. Your comment "...but my concern was that someLocalVariable itself depends on something that goes out of scope at the end of the method where all of this snippet is located, and that could possibly mess things up, right?" stresses my suspicion:
Yes someLocalVariable
would outlive SomeReallyLongLastingProcessingPipeline
but not necessarily the things you have pointed the char*
in your std::vector
to. Your problem is probably GottenFromSomewhere
, which fills your someLocalVariable
with pointers to things not alive when this whole lambda is executed. So it might live or might be already "dead" in the constructor of someLocalVariable
and the same is true for SomeReallyLongLastingProcessingPipeline
.
However this keeps speculation without your full code.
Use a std::vector<std::string>
instead.
Update from comments:
#include <iostream>
#include <future>
#include <string>
#include <vector>
#include <memory>
bool SomeReallyLongLastingProcessingPipeline(std::vector<const char*> data) {
return data.at(0)[0] == 'L';
}
//Prefer this one
bool SomeReallyLongLastingProcessingPipeline(std::vector<std::shared_ptr<const std::string>> data) {
return data.at(0)->find('L');
}
std::future<bool> foo() {
auto big_string_you_wont_change_until_lambda_finished = std::make_shared<std::string>("Long long text "
"(>should be at least several dozen kB");
//You could also use std::shared_ptr foo{new std::string("ff")}; but make_shared is safer (exception safety)
//beware of lambda capture, DO NOT just use [&] or [&big_string_you_wont_change_until_lambda_finished]
//use [=] or [big_string_you_wont_change_until_lambda_finished] is ok
std::future<bool> result = std::async(std::launch::async, [big_string_you_wont_change_until_lambda_finished]()
{
std::vector<const char*> someLocalVariable{big_string_you_wont_change_until_lambda_finished->c_str()};
std::vector<std::shared_ptr<const std::string>> someBetterLocalVariable
{big_string_you_wont_change_until_lambda_finished};
return SomeReallyLongLastingProcessingPipeline(someLocalVariable) || //I recommend the last one
SomeReallyLongLastingProcessingPipeline(someBetterLocalVariable);
});
return result;
}
int main() {
auto future = foo();
std::cout << future.get() << "\n";
return 0;
}