gpt4 book ai didi

c++ - 具有对象右值引用的线程

转载 作者:行者123 更新时间:2023-11-30 04:41:40 26 4
gpt4 key购买 nike

我有一个接受对象右值引用的函数,我想在 std::thread 中运行这个函数。下面一段代码

#include <iostream>
#include <thread>

class MyType {
public:
explicit MyType(int m) : myint_(m) {}
MyType(const MyType& ) = delete;
MyType ( MyType&& ) = delete;
MyType operator = (const MyType& ) = delete;
MyType operator = (const MyType&&) = delete;

private:
int myint_;
};

void Run(const MyType&& t) {
// do somthing with t.
}

int main()
{
MyType m{100};
std::thread t(Run, std::move(m));
t.join();
return 0;
}

我删除了默认的移动和复制构造函数。在我的例子中,可以定义一个默认的移动构造函数,但我不希望有一个复制构造函数,因为 sizeof(MyType) 可能很大,而且我担心复制构造函数是打电话。

我需要有关如何实现此目标的建议。

问候。

最佳答案

感谢@SamVarshavchik我现在可以使用 std::unique_ptr

#include <iostream>
#include <thread>

class MyType {
public:
explicit MyType(int m) : myint_(m) {}
MyType(const MyType& ) = delete;
MyType ( MyType&& ) = delete;
MyType operator = (const MyType& ) = delete;
MyType operator = (const MyType&&) = delete;

private:
int myint_;
};

void Run(std::unique_ptr<MyType>&& t) {
// do somthing with t.
}

int main()
{
auto m = std::make_unique<MyType>(100);
std::thread t(Run, std::move(m));
t.join();
return 0;
}

跟进问题:unique_ptr不可复制,只能移动。它如何与它一起工作但不适用于我的数据类型(即使我使其可移动)??

关于c++ - 具有对象右值引用的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59074443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com