加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: thread可移动,不可复制的参数

发布时间:2020-12-16 03:42:37 所属栏目:百科 来源:网络整理
导读:以下程序不会在VS11 beta,gcc 4.5或clang 3.1中构建 #include thread#include memoryint main() { std::unique_ptrint p; std::thread th([](std::unique_ptrint) { },std::move(p)); th.join();} 这是因为参数类型不可复制,但是实现尝试复制它. 据我所知,这
以下程序不会在VS11 beta,gcc 4.5或clang 3.1中构建
#include <thread>
#include <memory>

int main() {
    std::unique_ptr<int> p;
    std::thread th([](std::unique_ptr<int>) {

    },std::move(p));
    th.join();
}

这是因为参数类型不可复制,但是实现尝试复制它.

据我所知,这个方案很好,应该有效. std :: thread的要求似乎意味着可移动,不可复制的参数应该在这里工作.具体来说,它可以指出可调用对象和每个参数应满足MoveConstructible要求,INVOKE(DECAY_COPY(std :: forward< F>(f)),DECAY_COPY(std :: forward< Args>(args))… )应该是一个有效的表达式.

在这种情况下,我认为表达式的作用如下:

template <class T> typename std::decay<T>::type decay_copy(T&& v)
{ return std::forward<T>(v); }

std::unique_ptr<int> p;
auto f = [](std::unique_ptr<int>) {};

decay_copy(f)(decay_copy(std::move(p)));

我不认为这应该涉及一个p的副本. gcc至少可以编译这个表达式,虽然VS11没有.

我对我的要求有错误,论据必须是可复制的吗?
>标准在这个问题上留下任何余地来实现复制参数?
或者是我尝试不符合的实现?

解决方法

N3337的第30.3.1.2段第3和4段:

template <class F,class ...Args> explicit thread(F&& f,Args&&... args);

Requires: F and each Ti in Args shall satisfy the MoveConstructible requirements. INVOKE (DECAY_-COPY ( std::forward<F>(f)),DECAY_COPY (std::forward<Args>(args))...) (20.8.2) shall be a valid expression.

Effects: Constructs an object of type thread. The new thread of execution executes INVOKE (DECAY_-COPY ( std::forward<F>(f)),DECAY_COPY (std::forward<Args>(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread. Any return value from this invocation is ignored. [ Note: This implies that any exceptions not thrown from the invocation of the copy of f will be thrown in the constructing thread,not the new thread. —end note ] If the invocation of INVOKE (DECAY_COPY ( std::forward<F>(f)),DECAY_COPY (std::forward<Args>(args))...) terminates with an uncaught exception,std::terminate shall be called.

所以是的,这应该是正常的.如果没有,那么这是你的实现中的一个错误.

请注意,新线程上将发生任何参数移动/复制.您正在将引用传递给另一个线程,因此您需要确保它们仍然存在,直到该线程启动.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读