C++如何禁止掉对象的复制操作

本文介绍如何使用boost::noncopyable禁止类的拷贝构造和赋值操作,并探讨C++11中delete关键字的应用。

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

[cpp]  view plain  copy print?
  1. #ifndef BOOST_NONCOPYABLE_HPP_INCLUDED    
  2. #define BOOST_NONCOPYABLE_HPP_INCLUDED    
  3.     
  4. namespace boost {    
  5.     
  6. //  Private copy constructor and copy assignment ensure classes derived from    
  7. //  class noncopyable cannot be copied.    
  8.     
  9. //  Contributed by Dave Abrahams    
  10.     
  11. namespace noncopyable_  // protection from unintended ADL    
  12. {    
  13.   class noncopyable    
  14.   {    
  15.    protected:    
  16.       noncopyable() {}    
  17.       ~noncopyable() {}    
  18.    private:  // emphasize the following members are private    
  19.       noncopyable( const noncopyable& );    
  20.       const noncopyable& operator=( const noncopyable& );    
  21.   };    
  22. }    
  23.     
  24. typedef noncopyable_::noncopyable noncopyable;    
  25.     
  26. // namespace boost    
  27.     
  28. #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过了,那么重载该函数也是非法的,该函数我们习惯上称为删除函数。



本文转自莫水千流博客园博客,原文链接:http://www.cnblogs.com/zhoug2020/p/6591736.html,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值