c ++ std :: future未得到调用

问题描述 投票:0回答:2

我正在c ++中使用std::asyncstd::future,但是有点麻烦。当我运行此代码时,我希望看到(在stdout中)"hello world",但是我什么也没得到:

#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string>* test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ &a };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}

我使用指向未来的指针,因为在我的真实程序中,我有另一个结构代替std::string

struct A;
struct B;

typedef struct A {
  future<B>* b;
} A;

typedef struct B {
  A a;
} B;

即使我不使用指针,它也会给我这个错误:

error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::__cxx11::basic_string<char>]'

(对于上述错误,我知道我可以使用std :: move修复它,如here所示,但我需要使用指针)

所以我怎么才能实际从该程序获取"hello world"的输出?

c++ asynchronous future
2个回答
0
投票

callA()返回后,未来将被销毁,因此您拥有一个指向不再存在的对象的指针。如果希望从函数中将其作为指针返回,请使用std::unique_ptr

#include <iostream>
#include <future>
using namespace std;

struct A {
  unique_ptr<future<string>> test;
};

string getStr() {
  return "hello world";
}

A callA() {
  future<string> a = async(&getStr);

  return A{ std::make_unique<future<string>>(std::move(a)) };
}

int main() {
  A a = callA();
  cout << a.test->get() << endl;
}

0
投票

如果使用指针,则临时a将在函数的出口处销毁。因此您可以将自己的未来转移到您的结构上:

#include <iostream>
#include <future>
using namespace std;

struct A {
  future<string> test;
};

string getStr() {
  return "hello world";
}

A callA() {

  future<string> a = async(&getStr);

  return A{ std::move(a) };
}

int main() {
  A a = callA();
  cout << a.test.get() << endl;
}

如果由于某种原因必须使用指针-那么必须延长未来的寿命。 (例如,将Future添加到容器中,然后在使用Future之后将其从容器中删除)

© www.soinside.com 2019 - 2024. All rights reserved.