http://blog.csdn.net/huang_xw/article/details/8248960#
boost::noncopyable比較簡單, 主要用於單例的情況.
通常情況下, 要寫一個單例類就要在類的聲明把它們的構造函數, 賦值函數, 析構函數, 復制構造函數隱藏到private或者protected之中, 每個類都這么做麻煩.
有noncopyable類, 只要讓單例類直接繼承noncopyable.
class noncopyable的基本思想是把構造函數和析構函數設置protected權限,這樣子類可以調用,但是外面的類不能調用,那么當子類需要定義構造函數的時候不至於通不過編譯。但是最關鍵的是noncopyable把復制構造函數和復制賦值函數做成了private,這就意味着除非子類定義自己的copy構造和賦值函數,否則在子類沒有定義的情況下,外面的調用者是不能夠通過賦值和copy構造等手段來產生一個新的子類對象的。
#ifndef BOOST_NONCOPYABLE_HPP_INCLUDED #define BOOST_NONCOPYABLE_HPP_INCLUDED namespace boost { // Private copy constructor and copy assignment ensure classes derived from // class noncopyable cannot be copied. // Contributed by Dave Abrahams namespace noncopyable_ // protection from unintended ADL { class noncopyable { protected: noncopyable() {} ~noncopyable() {} private: // emphasize the following members are private noncopyable( const noncopyable& ); const noncopyable& operator=( const noncopyable& ); }; } typedef noncopyable_::noncopyable noncopyable; } // namespace boost #endif // BOOST_NONCOPYABLE_HPP_INCLUDED
#include "tfun.h" class myclass: public boost::noncopyable { public: myclass(){}; myclass(int i){}; }; int main() { myclass cl1(); myclass cl2(1); // myclass cl3(cl1); // error // myclass cl4(cl2); // error return 0; }