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

猜你喜欢

转载自blog.csdn.net/zhangxiong1985/article/details/84432041
今日推荐