【Boost】boost::noncopyable介紹

來源:互聯網
上載者:User

boost::noncopyable比較簡單, 主要用於單例的情況.
通常情況下, 要寫一個單例類就要在類的聲明把它們的建構函式, 賦值函數, 解構函式, 複製建構函式隱藏到private或者protected之中, 每個類都這麼做麻煩.
有noncopyable類, 只要讓單例類直接繼承noncopyable.
class noncopyable的基本思想是把建構函式和解構函式設定protected許可權,這樣子類可以調用,但是外面的類不能調用,那麼當子類需要定義建構函式的時候不至於通不過編譯。但是最關鍵的是noncopyable把複製建構函式和複製賦值函數做成了private,這就意味著除非子類定義自己的copy構造和賦值函數,否則在子類沒有定義的情況下,外面的調用者是不能夠通過賦值和copy構造等手段來產生一個新的子類對象的。

#ifndef BOOST_NONCOPYABLE_HPP_INCLUDED#define BOOST_NONCOPYABLE_HPP_INCLUDEDnamespace boost {//  Private copy constructor and copy assignment ensure classes derived from//  class noncopyable cannot be copied.//  Contributed by Dave Abrahamsnamespace 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);// errorreturn 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.