【问题标题】:Why does make_unique of a struct fail when containing an std::promise as member?为什么包含 std::promise 作为成员时结构的 make_unique 会失败?
【发布时间】:2016-12-16 15:49:52
【问题描述】:

我编写了结构体MyParam,以便它可以使用任意数量的参数进行实例化,在本例中为intbool。出于封装原因,我希望MyParams 包含自己的promise,以便它可以在完成某项操作时进行报告。但是当我将语句添加到结构时,它失败了。不过,作为一个全球性的,它工作得很好。代码如下:

#include <tuple>
#include <memory>
#include <future>

//std::promise< bool > donePromise; // OK: if at global level, then make_unique error goes away

template< typename... ArgsT >
struct MyParams
{
  MyParams( ArgsT... args ) : rvalRefs { std::forward_as_tuple( args... ) } {}

  std::tuple< ArgsT... > rvalRefs;
  std::promise< bool > donePromise; // causes make_unique to fail when donePromise is a member of MyParams
};

int main()
{
  int num { 33 };
  bool tf { false };
  MyParams< int, bool > myParams( num, tf ); // OK
  auto myParamsUniquePtr = std::make_unique< MyParams< int, bool > >( myParams );

  std::future< bool > doneFuture = myParams.donePromise.get_future(); // OK: when donePromise is a global

  return 0;
}
error C2280: 'MyParams<int,bool>::MyParams(const MyParams<int,bool> &)': attempting to reference a deleted function

关于promise 声明作为会员,我缺少什么?

【问题讨论】:

    标签: c++ c++14 unique-ptr


    【解决方案1】:

    std::promise 不可复制构造。

    std::make_unique< MyParams< int, bool > >( myParams )
    

    在上面,make_unique 正在尝试复制构造一个 MyParams&lt; int, bool &gt;,由于存在 promise 数据成员,它的格式不正确。如果您改为移动构造,则可以编译代码。

    std::make_unique< MyParams< int, bool > >( std::move(myParams) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 2012-12-02
      • 1970-01-01
      • 2015-10-29
      • 2010-09-23
      相关资源
      最近更新 更多