最容易想到的是将拷贝构造函数与赋值函数声明为private。但是,private只是说外部不能直接调用,但是可以间接通过类的成员函数与友元函数对其访问。那么怎么办呢?

----》在类中,允许声明函数,但是,可以不用实现该函数,这是合法的。那么即使是在public中声明函数,但是不实现,那么调用这个函数也是会出错的。

那么好了我们可以特性一起使用,boost::noncopyable

  1. #ifndef BOOST_NONCOPYABLE_HPP_INCLUDED
  2. #define BOOST_NONCOPYABLE_HPP_INCLUDED
  3. namespace boost {
  4. //  Private copy constructor and copy assignment ensure classes derived from
  5. //  class noncopyable cannot be copied.
  6. //  Contributed by Dave Abrahams
  7. namespace noncopyable_  // protection from unintended ADL
  8. {
  9. class noncopyable
  10. {
  11. protected:
  12. noncopyable() {}
  13. ~noncopyable() {}
  14. private:  // emphasize the following members are private
  15. noncopyable( const noncopyable& );
  16. const noncopyable& operator=( const noncopyable& );
  17. };
  18. }
  19. typedef noncopyable_::noncopyable noncopyable;
  20. } // namespace boost
  21. #endif  // BOOST_NONCOPYABLE_HPP_INCLUDED

为了禁止拷贝对象,我们只需要让其私有继承自boost::noncopyable,

class student:private boost::noncopyable

{

......

}

当调用到派生类的拷贝构造函数或赋值函数进行复制时,不可避免的要调用基类对应的函数,因为这些操作是private,这样的操作会被编译器拒绝。

需要注意,多重继承有时会使空基类noncopyable优化失效,所以这不适合用于多重继承的情形。

另外,如果只是不想要使用默认的拷贝构造函数或赋值函数,可以使用C++11提供的delete,

class MyClass
{
  public:
    MyClass()=default;
    MyClass(const MyClass& )=delete;
  ......
}

当然,一旦函数被delete过了,那么重载该函数也是非法的,该函数我们习惯上称为删除函数。

最新文章

  1. 使用 Json.Net 对Json文本进行 增删改查
  2. 前端CSS规范整理_转载、、、
  3. IO(三)----序列流
  4. 第一个 bat 文件
  5. SIM卡基础,各管脚意义,封装定义
  6. struts2 日期标签
  7. Uva 572 Oil Deposits
  8. 【USACO】接住苹果
  9. php学习的第8天
  10. Java.nio-随机读写汉字
  11. Android测试(四):Instrumented 单元测试
  12. 将arguments转换成数组的方法
  13. WC2019 划水记
  14. Spark中map与flatMap
  15. Performance Tuning Guidelines for Windows Server 2012
  16. 要学习的UML图
  17. ubuntu 添加CDROM安装源
  18. (四)SSO之CAS框架单点登录,自定义验证登录方式
  19. Iterable/Iterator傻傻分不清
  20. Scrum立会报告+燃尽图(十月二十日总第十一次)

热门文章

  1. 苹果笔记本适合什么人 中国Mac电脑用户的8个事实
  2. Java中String和byte[]间的转换浅析
  3. [HNOI2003]消防局的设立 树形dp // 贪心
  4. 4.工厂方法模式(Factory Method)
  5. 立个Flag不学好PHP誓不罢休
  6. 【1】【leetcode-33,81】 搜索旋转排序数组
  7. dependencies和devDependencies两者区别
  8. Tornado基本应用
  9. Lua 函数链功能
  10. mysql 约束和外键约束实例