【问题标题】:std::make_unique<std::thread> with lambda带有 lambda 的 std::make_unique<std::thread>
【发布时间】:2015-01-12 18:42:45
【问题描述】:

我正在尝试在 Visual Studio 2013 上编译以下代码:

std::unique_ptr<std::thread> threadPtr;
threadPtr.reset(std::make_unique<std::thread>([&]
{
  //...

}));

失败并出现错误:

error C2664: 'void std::unique_ptr<std::thread,std::default_delete<_Ty>>::
    reset(std::thread *) throw()' : cannot convert argument 1 from 
    'std::unique_ptr<std::thread,std::default_delete<_Ty>>' to 'std::thread *'

这似乎很奇怪,因为我在其他地方使用std::make_unique 没有问题。但是,当我不使用 std::make_unique 而是使用 new 时,它可以工作:

std::unique_ptr<std::thread> threadPtr;
threadPtr.reset(new std::thread([&]
{
  //...

}));

我在这里做错了什么,还是编译器的问题?

【问题讨论】:

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


    【解决方案1】:

    std::make_unique 返回一个std::unique_ptr。但是std::unique_ptr::reset 需要一个指针。所以你要找的是:

    std::unique_ptr<std::thread> threadPtr(std::make_unique<std::thread>([&]
    {
      //...
    
    }));
    

    或:

    threadPtr.reset(std::make_unique<std::thread>([&]
    {
      //...
    
    }).release());
    

    【讨论】:

    • 好电话。那你也可以用threadPtr = std::make_unique...吗?
    • @NicolasHolthaus 自动,是的。
    猜你喜欢
    • 1970-01-01
    • 2015-05-19
    • 1970-01-01
    • 2017-02-20
    • 2023-04-07
    • 2015-03-25
    • 2022-10-18
    • 2014-02-26
    • 1970-01-01
    相关资源
    最近更新 更多