文章參考了這里http://blog.csdn.net/huang_xw/article/details/8248960
boost::noncopyable 比較簡(jiǎn)單, 主要用于單例的情況.
通常情況下, 要寫(xiě)一個(gè)單例類(lèi)就要在類(lèi)的聲明把它們的構(gòu)造函數(shù), 賦值函數(shù), 析構(gòu)函數(shù), 拷貝構(gòu)造函數(shù)隱藏到 private 或者 protected 之中, 每個(gè)類(lèi)都這么干的話(huà)會(huì)非常地麻煩.
但是有了 noncopyable 類(lèi)之后, 只要讓單例類(lèi)直接繼承 noncopyable, 一切都會(huì)迎刃而解.
class noncopyable 的基本思想是把構(gòu)造函數(shù)和析構(gòu)函數(shù)設(shè)置 protected 權(quán)限,這樣子類(lèi)可以調(diào)用,但是外面的類(lèi)不能調(diào)用,那么當(dāng)子類(lèi)需要定義構(gòu)造函數(shù)的時(shí)候不至于通不過(guò)編譯。但是最關(guān)鍵的是noncopyable 把復(fù)制構(gòu)造函數(shù)和復(fù)制賦值函數(shù)做成了 private,這就意味著 除非子類(lèi)定義自己的copy構(gòu)造和賦值函數(shù),否則在子類(lèi)沒(méi)有定義的情況下,外面的調(diào)用者是不能夠通過(guò)賦值和copy構(gòu)造等手段來(lái)產(chǎn)生一個(gè)新的子類(lèi)對(duì)象的。
如果代碼中沒(méi)有子類(lèi)的賦值或者拷貝操作,編譯器是不會(huì)為我們生成默認(rèn)的賦值函數(shù)和拷貝構(gòu)造函數(shù)的,一旦代碼中出現(xiàn)了這些操作,而子類(lèi)并沒(méi)有定義自己的copy構(gòu)造函數(shù)和賦值函數(shù),那么編譯器試圖為子類(lèi)生成,生成的函數(shù)首先要調(diào)用父類(lèi)的copy構(gòu)造函數(shù)或者賦值函數(shù),而這兩個(gè)函數(shù)都為 private 類(lèi)型,自然是無(wú)法訪(fǎng)問(wèn)的,因此在編譯器就會(huì)報(bào)錯(cuò).
#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
給一個(gè)示例:
#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;
}