c++之packaged_task和future实现异步效果

image



class CObject {
public:
	CObject(string str) :m_str(unique_ptr<string>(new string(str))) {

		cout << "构造函数" << endl;
	}
	~CObject() {
		if (m_str)
			cout << "析构函数: " << *m_str << " [" << this << "]" << endl;
		else
			cout << "析构函数: (moved) [" << this << "]" << endl;
	}
	CObject(const CObject& obj) {
		m_str = make_unique<string>(*obj.m_str);
		cout << "拷贝构造函数" << endl;
	}

	CObject(CObject&& obj) noexcept {
		m_str = move(obj.m_str);
		cout << "移动构造函数" << endl;
	}
	CObject* show() {
		cout << "m_str=" << *m_str << endl;
		return this;
	}
	CObject* show_error() {
		cout << "this is error" << endl;
		return this;
	}

	void operator()(int num) {
		cout << "num=" << num << endl;
	}
	void update_str(char *str) {

		*m_str = string(str);
	}

private:

	unique_ptr<string>m_str;

};

调用:

		std::packaged_task<CObject(string)> task([](string str) {
			return CObject(str); });
		std::future<CObject> fut = task.get_future();
		std::thread t(std::move(task),"萧海");  // 任务交给线程执行
		CObject obj=move( fut.get());
		obj.show();
		t.join();
posted @ 2025-11-24 16:16  我不是萧海哇~~~  阅读(10)  评论(0)    收藏  举报