创建类的唯一实例。 然而客户使用颇多麻烦。类count是客户代码。 无 #include iostream#include threadnamespace mc {templateclass Valueclass singleton{protected:singleton() = default;singleton(const singleton) = delete;~singleton() = default;publ
然而客户使用颇多麻烦。类 count 是客户代码。 <无>
#include <iostream> #include <thread> namespace mc { template<class Value> class singleton { protected: singleton() = default; singleton(const singleton&) = delete; ~singleton() = default; public: typedef Value value_type; static value_type* instance() { static value_type only_one; return &only_one; } }; } class count final //如果不设置 final, 错误例3可以编译通过 : public mc::singleton<count> { public: void print() {std::cout << ++n << std::endl;} private: friend mc::singleton<count>; // 设为友元是客户的责任 count(){} //将构造函数设为 private 是客户的责任。 ~count(){} static int n; }; int count::n = 0; void func(const char* id) { auto c = count::instance(); std::cout << "thread_id: " << id << " count: "; c->print(); //count e1 = *c; // error //count e2; // error //struct e3 : count {}; // error } int main(void) { std::thread t1(func, "t1"); std::thread t2(func, "t2"); std::thread t3(func, "t3"); t1.join(); t2.join(); t3.join(); return 0; }