1. 程式人生 > >Boost中Core模組的noncopyable用法

Boost中Core模組的noncopyable用法

標頭檔案

boost/noncopyable.hpp

作用

noncopyable能讓繼承它的子類,不具備 拷貝構造及賦值構造 的功能。

舉例

#include <boost/noncopyable.hpp>
#include <iostream>

//  This program demonstrates compiler errors resulting from trying to copy
//  construct or copy assign a class object derived from class noncopyable.

namespace
{
    class DontTreadOnMe : private boost::noncopyable
    {
    public:
         DontTreadOnMe() { std::cout << "defanged!" << std::endl; }
    };   // DontTreadOnMe

}   // unnamed namespace

int main()
{
    DontTreadOnMe object1;
    DontTreadOnMe object2(object1);
    object1 = object2;
    return 0;
}   // main

以上程式碼,編譯不通過。

原始碼

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:
#if !defined(BOOST_NO_CXX11_DEFAULTED_FUNCTIONS) && !defined(BOOST_NO_CXX11_NON_PUBLIC_DEFAULTED_FUNCTIONS)
      BOOST_CONSTEXPR noncopyable() = default;
      ~noncopyable() = default;
#else
      noncopyable() {}
      ~noncopyable() {}
#endif
#if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS)
      noncopyable( const noncopyable& ) = delete;
      noncopyable& operator=( const noncopyable& ) = delete;
#else
  private:  // emphasize the following members are private
      noncopyable( const noncopyable& );
      noncopyable& operator=( const noncopyable& );
#endif
  };
}

typedef noncopyable_::noncopyable noncopyable;

} // namespace boost