0

在以下代码段中:

std::future<bool> result = std::async(std::launch::async, []()
{
    std::vector<char*> someLocalVariable{GottenFromSomewhere()};
    return SomeReallyLongLastingProcessingPipeline(someLocalVariable);
});

我倾向于说这someLocalVariable无疑会比SomeReallyLongLastingProcessingPipeline()调用更长寿,即使这一切都发生在传递给 std::async 的 lambda 中。这是真的?

我不得不提到的std::future是在一个对象内部,该对象在该函数退出之前构建SomeReallyLongLastingProcessingPipeline()并在该函数退出后被破坏。

4

1 回答 1

2

就其本身而言,您发布的代码似乎还可以而且是无辜的,但是std::vectorchar*我感到怀疑。您的评论“......但我担心的是 someLocalVariable 本身依赖于在所有此代码段所在的方法末尾超出范围的东西,这可能会搞砸,对吧?” 强调我的怀疑:

是的someLocalVariableSomeReallyLongLastingProcessingPipeline但不一定是你指出的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;
}   
于 2019-02-12T17:54:36.720 回答