需要谨慎防止被保护的对象意外泄露到外界函数被更改状态。代码示例如下:
#include#include #include #include #include struct TData { public: int n; std::string str; public: TData() { n = 0; str = "Moutain River"; } }; class CDataWrapper { TData data; std::mutex mt; public: void processData(std::function func) { mt.lock(); func(data.n, data.str); mt.unlock(); } }; void func(const int& n, const std::string& str) { std::cout << n << std::endl; std::cout << str.c_str() << std::endl; } CDataWrapper* pdw = nullptr; void task() { if (pdw != nullptr) pdw->processData(func); } int main() { CDataWrapper dw; pdw = &dw; std::thread t(task); t.join(); return 0; }



