首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按‘`std::`scoped_thread`’值传递的`scoped_thread`

按‘`std::`scoped_thread`’值传递的`scoped_thread`
EN

Stack Overflow用户
提问于 2016-05-16 21:44:35
回答 1查看 201关注 0票数 0

我看到了以下的实现

运行中的c++并发

scoped_thread的设计是让它实际拥有线程的所有权。

代码语言:javascript
复制
class scoped_thread
{
    std::thread t;
public:
    explicit scoped_thread( std::thread t_ ) :
        t( std::move( t_ ) )
    {
        if ( !t.joinable() )
            throw std::logic_error( "thread is not joinable" );
    }

    ~scoped_thread()
    {
        t.join();
    }
    scoped_thread( scoped_thread const& ) = delete;
    scoped_thread& operator=( scoped_thread const& ) = delete;
};

用法示例:

代码语言:javascript
复制
struct func;
void f()
{
    int some_local_state;
    scoped_thread t(std::thread(func(some_local_state)));
    do_something_in_current_thread();
}

如果调用方使用以下代码,会发生什么情况?

代码语言:javascript
复制
struct func;
void f()
{
    int some_local_state;
    std::thread t1(func(some_local_state));
    scoped_thread t(t1);  // pass by value
    do_something_in_current_thread();
}

我担心的是,pass by value将导致scoped_thread不拥有线程t1。

有人能帮我澄清一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-16 21:46:27

scoped_thread t(t1);//按值传递

这不会编译,因为std::thread是不可复制的(因为它有一个移动构造函数,但没有复制构造函数)。

从现有的scoped_thread构建std::thread的唯一方法是移动它,它转移所有权:

代码语言:javascript
复制
scoped_thread t(std::move(t1));

所以你不需要担心。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37263758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档