首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::packaged_task::packaged_task

packaged_task();

(1)

(since C++11)

template <class F> explicit packaged_task( F&& f );

(2)

(since C++11)

template <class F, class Allocator> explicit packaged_task( std::allocator_arg_t, const Allocator& a, F&& f );

(3)

(since C++11) (until C++17)

packaged_task( const packaged_task& ) = delete;

(4)

(since C++11)

packaged_task( packaged_task&& rhs );

(5)

(since C++11)

构造一个新的std::packaged_task对象。

1%29构造一个std::packaged_task对象,没有任务和共享状态。

2%29构造一个std::packaged_task对象具有共享状态和任务的副本,并在std::forward<F>(f)此构造函数不参与重载解决方案。std::decay<F>::type是与std::packaged_task<R(ArgTypes...)>...

3%29构造一个std::packaged_task对象具有共享状态和任务的副本,并在std::forward<F>(f)使用提供的分配器分配存储任务所需的内存。如果下列情况下,此构造函数不参与重载解析。std::decay<F>::type是与std::packaged_task<R(ArgTypes...)>...

4%29复制构造函数被删除,std::packaged_task只能移动。

5%29构造一个std::packaged_task的共享状态和任务rhs,离开rhs没有共享状态和移出任务。

参数

f

-

the callable target (function, member function, lambda-expression, functor) to execute

a

-

the allocator to use when storing the task

rhs

-

the std::packaged_task to move from

例外

1%29

noexcept规格:

noexcept

2%29复制/移动构造函数引发的任何异常。f也有可能std::bad_alloc如果分配失败。

3%29复制/移动构造函数引发的任何异常。f并由分配器%27sallocate如果内存分配失败,则启动。

4%29%280%29

5%29

noexcept规格:

noexcept

缺陷报告

以下行为更改缺陷报告追溯应用于先前发布的C++标准。

DR

Applied to

Behavior as published

Correct behavior

LWG 2067

C++11

the deleted copy constructor took reference to non-const

made const

二次

代码语言:javascript
复制
#include <future>
#include <iostream>
#include <thread>
 
int fib(int n)
{
    if (n < 3) return 1;
    else return fib(n-1) + fib(n-2);
}
 
int main()
{
    std::packaged_task<int(int)> fib_task(&fib); 
 
    std::cout << "starting task\n";
    auto result = fib_task.get_future();
    std::thread t(std::move(fib_task), 40);
 
    std::cout << "waiting for task to finish...\n";
    std::cout << result.get() << '\n';
 
    std::cout << "task complete\n";
    t.join();
}

二次

产出:

二次

代码语言:javascript
复制
starting task
waiting for task to finish...
102334155
task complete

二次

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com