【问题标题】:std::thread in constructor referencing it's deleted copy constructor?构造函数中的 std::thread 引用它已删除的复制构造函数?
【发布时间】:2022-01-22 12:49:00
【问题描述】:

我在编写一个构造函数时遇到了很多麻烦。这是非常基本的东西,但我今天过得很糟糕,因为我完全被难住了。

class RenderThread {
public:
    RenderThread(std::thread && threadToGive) 
        : m_renderThread(threadToGive) {}

private:
    std::thread m_renderThread;
};


int test() {
    std::thread thread;
    RenderThread rt(std::move(thread));
}

我的构造函数试图调用std::thread::thread(const std::thread &) 这绝对不是我的目标,即使它是可能的。我想将参数threadToGive 移动到m_renderThread,而不是复制它。我在这里做错了什么?

【问题讨论】:

  • 试试RenderThread(std::thread && threadToGive) : m_renderThread(std::move(threadToGive)) {}
  • @songyuanyao - 哦,天哪,就是这样。我认为在Type && 的对象上使用std::move 是多余的,但我想我错了。谢谢。
  • threadToGive 本身就是一个左值,即使它的类型是右值引用。值类别和类型是两个独立的属性。

标签: c++ constructor move


【解决方案1】:

你必须将std::move()RenderThread构造函数的参数转化为m_renderThread的构造函数成员:

   : m_renderThread(std::move(threadToGive)) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2013-08-19
    相关资源
    最近更新 更多