I have a function which accepts an rvalue reference of on object and I want to run this function in a std::thread
. Following piece of code
#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;
}
I have deleted the default move and copy constructor. In my case it might be possible to define a default move constructor but I would not like to have a copy constructor because sizeof(MyType)
can be big and I am concerned about the memory when the copy constructors are called.
I need advice on how to achieve this.
Regards.
Thanks to @SamVarshavchik I have it working now with 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;
}
Follow up question: unique_ptr is not copyable and is only moveable. How does it works with it but not for my data type (even though I make it moveable) ??