class T {
public:
int get() { return t; }
void set(int num) { t = num; }
T():t(1) {}
private:
int t; };
std::mutex g_mut;
std::shared_ptr<T> g_ptr;
void func(const std::shared_ptr<T>& pt) { std::cout<<pt->get(); }
void setFunc(const std::shared_ptr<T>& pt,int num) { pt->set(num); }
void read()
{
std::shared_ptr<T> localPtr;
{
std::lock_guard<std::mutex> lock(g_mut);
localPtr = g_ptr;
}
func(localPtr);
}
void write(int num)
{
std::shared_ptr<T> newPtr(new T);
{
std::lock_guard<std::mutex> lock(g_mut);
g_ptr = newPtr;
}
setFunc(newPtr, num);
}
int main()
{
g_ptr = std::shared_ptr<T>(new T);
write(2);
read();
return 0;
}