就其本身而言,您发布的代码似乎还可以而且是无辜的,但是std::vector
让char*
我感到怀疑。您的评论“......但我担心的是 someLocalVariable 本身依赖于在所有此代码段所在的方法末尾超出范围的东西,这可能会搞砸,对吧?” 强调我的怀疑:
是的someLocalVariable
,SomeReallyLongLastingProcessingPipeline
但不一定是你指出的char*
东西std::vector
。你的问题可能是,当整个 lambda 被执行时GottenFromSomewhere
,它会用指向不存在的东西的指针填充你。someLocalVariable
所以它可能在构造函数中存活或已经“死亡”,someLocalVariable
对于SomeReallyLongLastingProcessingPipeline
.
但是,这会在没有完整代码的情况下进行猜测。
改用 a std::vector<std::string>
。
评论更新:
#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;
}