随笔 - 741  文章 - 0  评论 - 260  阅读 - 416万

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

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

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


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

  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过了,那么重载该函数也是非法的,该函数我们习惯上称为删除函数。

posted on   莫水千流  阅读(470)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2013-03-20 float compare 0
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示