c++ - std::promise 可以从非 POD 对象生成吗?

标签 c++ asynchronous promise

我的应用程序所做的其中一件事是监听和接收来自套接字的有效负载。我从不想阻止。在收到的每个有效负载上,我想创建一个对象并将其传递给工作线程,直到稍后再忘记它,这就是原型(prototype)代码的工作方式。但是对于生产代码,我想通过使用方便的异步方法来降低复杂性(我的应用程序很大)。 async 从 promise 中获取 future 。为此,我需要在下面由 Xxx 类表示的非 POD 对象上创建一个 promise 。我看不到有任何方法可以做到这一点(请参阅下面我的示例代码中的错误)。这里用async合适吗?如果是这样,我如何构建一个比 int 更复杂的 promise/future 对象(我看到的所有代码示例都使用 int 或 void):

#include <future>
class Xxx //non-POD object
{
  int i;
public:
  Xxx( int i ) : i( i ) {}
  int GetSquare() { return i * i; }
};

int factorial( std::future< Xxx > f )
{
  int res = 1;
  auto xxx = f.get();
  for( int i = xxx.GetSquare(); i > 1; i-- )
  {
    res *= i;
  }
  return res;
}

int _tmain( int argc, _TCHAR* argv[] )
{
  Xxx xxx( 2 ); // 2 represents one payload from the socket
  std::promise< Xxx > p; // error: no appropriate default constructor available
  std::future< Xxx > f = p.get_future();
  std::future< int > fu = std::async( factorial, std::move( f ) );
  p.set_value( xxx );
  fu.wait();
  return 0;
}

最佳答案

正如 Mike 已经回答的那样,这绝对是 std::promise 的 Visual C++ 实现中的错误,您正在做的应该有效。

但我很好奇为什么您仍然需要这样做。也许有一些其他要求您没有显示以保持示例简单,但这是编写该代码的明显方式:

#include <future>

class Xxx //non-POD object
{
  int i;
public:
  Xxx( int i ) : i( i ) {}
  int GetSquare() { return i * i; }
};

int factorial( Xxx xxx )
{
  int res = 1;
  for( int i = xxx.GetSquare(); i > 1; i-- )
  {
    res *= i;
  }
  return res;
}

int main()
{
  Xxx xxx( 2 ); // 2 represents one payload from the socket
  std::future< int > fu = std::async( factorial, std::move( xxx ) );
  int fact = fu.get();
}

关于c++ - std::promise 可以从非 POD 对象生成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991694/

相关文章:

c++ - C++原子compare_exchange_weak

c++ - 具有非模板基类的模板类

javascript - 如何/是否重写异步 :false AJAX function?

asynchronous - 关于 .Net Tasks 和 Async CTP 的问题

mysql - 在并行模式下使用同一事务运行多个查询是一种不好的做法吗?

javascript - Promise.all 不会捕获错误

c++ - 在 unordered_map<vector<T>> 中使用 lambda 函数进行散列

c++ - 如何找到内存泄漏的位置?

javascript - 函数 displayOpenXAds() 未定义

javascript - Promise 控制流 (es2015),具有复杂的参数依赖性