参考资料
链接:恋恋风辰官方博客
复制构造or移动构造
#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <future>
class TestCopy
{
public:
TestCopy(){}
TestCopy(const TestCopy& tp)
{
std::cout << "Test copy copy. \n";
}
TestCopy(TestCopy&& cp)
{
std::cout << "Test copy move. \n";
}
};
TestCopy test_copy()
{
TestCopy tp;
return tp;
}
int main()
{
// 1. 测试默认是移动构造还是拷贝构造
auto obj = test_copy(); // 默认是移动构造
std::cout << "Finished! \n";
}
测试结果:
线程归属权问题
#include <iostream>
#include <thread>
#include <memory>
#include <functional>
#include <future>
void thread_ops()
{
std::thread t1([]() {
int i = 0;
while (i < 5)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
i++;
}
});
std::thread t2([]() {
int i = 0;
while (i < 10)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
i++;
}
});
t1 = std::move(t2);
t1.join();
t2.join();
}
int main()
{
// 2. 线程归属权问题: 不能将线程转移给一个已经绑定的变量
thread_ops();
std::cout << "Finished! \n";
}