1  缺省函数

设计一个类,没有成员函数 (member function),只有成员数据 (member data)

  1. class DataOnly {
  2. private:
  3. std::string strName;  // member data
  4. int   iData;
  5. };

1.1  特殊成员函数

C++98 编译器会为其隐式的产生四个函数:缺省构造函数析构函数拷贝构造函数拷贝赋值算子

  而 C++11 编译器,除了产生这四个函数外,还会多产生两个函数:移动构造函数移动赋值算子

  1. #include <iostream>
  2.  
  3. class DateOnly
  4. {
  5. private:
  6. std::string strName;
  7. int iDate;
  8. public:
  9. DateOnly();
  10. DateOnly(std::string _str, int _iDate);
  11. ~DateOnly();
  12.  
  13. DateOnly(const DateOnly& rhs);
  14. DateOnly& operator=(const DateOnly& rhs);
  15.  
  16. DateOnly(const DateOnly&& rhs);
  17. DateOnly& operator=(const DateOnly&& rhs);
  18. };
  19.  
  20. DateOnly::DateOnly(std::string _str, int _iDate) :strName(_str), iDate(_iDate){}
  21.  
  22. DateOnly::DateOnly(const DateOnly& rhs)
  23. {
  24. strName = rhs.strName;
  25. iDate = rhs.iDate;
  26. }
  27.  
  28. DateOnly& DateOnly::operator=(const DateOnly& rhs)
  29. {
  30. this->strName = rhs.strName;
  31. this->iDate = rhs.iDate;
  32. return *this;
  33. }

1.2  两个实现形式

缺省构造函数,是为了初始化类的成员数据,相当于如下形式:

  1. DataOnly::DataOnly(const DataOnly &orig): strName(orig.strName), iData(orig.iData) { }

拷贝赋值算子的实现,则相当于如下形式:

 
  1. DataOnly& DataOnly::operator=(const DataOnly &rhs)
  2. {
  3. strName = rhs.strName; // calls the string::operator=
  4. iData = rhs.iData; // uses the built-in int assignment
  5.  
  6. return *this; // return a reference to this object
  7. }
 

结尾为何返回 *this,可以参见另一篇博文 C++ 之 重载赋值操作符  中的 “1.1  链式赋值”

2  禁止缺省函数

作为开发者,如果不想让用户使用某个类成员函数,不声明该函数即可;但对于由编译器自动产生的特殊成员函数 (special member fucntions),则是另一种情况。

例如,设计一个树叶类,如下所示:

  1. class LeafFromTree{ ... };

莱布尼茨说过,“世上没有两片完全相同的树叶” (Es gibt keine zwei Blätter, die gleich bleiben),因此,对于一片独一无二的树叶,下面的操作是错误的。

  1. LeafFromTree leaf1;
  2. LeafFromTree leaf2;
  3. LeafFromTree Leaf3(Leaf1); // attempt to copy Leaf1 — should not compile!
  4. Leaf1 = Leaf2; // attempt to copy Leaf2 — should not compile!

由以上代码可知,此时需要避免使用 “拷贝构造函数” 和 “拷贝赋值算子”

2.1  私有+不实现

C++98 中,可声明这些特殊成员函数为私有型 (private),且不实现该函数,具体如下:

  1. class LeafFromTree{
  2. private:
  3. LeafFromTree( const LeafFromTree& );        // not defined
  4. LeafFromTree & operator=( const LeafFromTree& ); // not defined
  5. };

程序中如果调用了 LeafFromTree 类的拷贝构造函数 (或拷贝赋值操作符),则在编译时,会出现链接错误 (link-time error)

为了将报错提前到编译时 (compile time),可增加了一个基类 Uncopyable,并将拷贝构造函数和拷贝赋值算子声明为私有型

 
  1. class Uncopyable {
  2. protected:       
  3. Uncopyable() {}    // allow construction and destruction of derived objects...
  4. ~Uncopyable() {}
  5. private:
  6. Uncopyable(const Uncopyable&);  // ...but prevent copying
  7. Uncopyable& operator=(const Uncopyable&);
  8. };
 

而 LeafFromTree 则私有继承自 Uncopyable 基类

  1. // class no longer declares copy ctor or copy assign operator
  2. class LeafFromTree: private Uncopyable { };

2.2  delete 关键字

C++11 中比较简单,只需在想要 “禁止使用” 的函数声明后加 “= delete”,需要保留的则加 "= default" 或者不采取操作

 
  1. class LeafFromTree{
  2. public:
  3.   LeafFromTree() = default;
      ~LeafFromTree() = default;
  4.  
  5.   LeafFromTree( const LeafFromTree& ) = delete;  // mark copy ctor or copy assignment operator as deleted functions
  6.   LeafFromTree & operator=( const LeafFromTree &) = delete;
    };
 

3  delete 的扩展

  C++11 中,delete 关键字可用于任何函数,不仅仅局限于类成员函数

3.1  函数重载

在函数重载中,可用 delete 来滤掉一些函数的形参类型,如下:

  1. bool isLucky(int number); // original function
  2. bool isLucky(char) = delete; // reject chars
  3. bool isLucky(bool) = delete; // reject bools
  4. bool isLucky(double) = delete; // reject doubles and floats

  这样在调用 isLucky 函数时,如果参数类型不对,则会出现错误提示

  1. if (isLucky('a')) // error ! call to deleted function
  2. if (isLucky(true)) // error !
  3. if (isLucky(3.5)) // error !

3.2  模板特化

在模板特例化中,也可以用 delete 来过滤一些特定的形参类型。

例如,Widget 类中声明了一个模板函数,当进行模板特化时,要求禁止参数为 void* 的函数调用。

如果按照 C++98 的 “私有不实现“ 思路,应该是将特例化的函数声明为私有型,如下所示:

 
  1. class Widget {
  2. public:
  3. template<typename T>
  4. void processPointer(T* ptr) { }
  5. private:
  6. template<>
  7. void processPointer<void>(void*); // error!
  8. };
 

问题是,模板特化应该被写在命名空间域 (namespace scope),而不是类域 (class scope),因此,该方法会报错。

而在 C++11 中,因为有了 delete 关键字,则可以直接在类域外,将特例化的模板函数声明为 delete, 如下所示:

 
  1. class Widget {
  2. public:
  3. template<typename T>
  4. void processPointer(T* ptr) { }
  5. };
  6.  
  7. template<>
  8. void Widget::processPointer<void>(void*) = delete; // still public, but deleted
 

这样,当程序代码中,有调用 void* 作形参的 processPointer 函数时,则编译时就会报错。

C++11 之 " = delete "的更多相关文章

  1. C++11 之 &quot; = delete &quot;

    1  缺省函数 设计一个类,没有成员函数 (member function),只有成员数据 (member data) class DataOnly { private: std::string st ...

  2. Ubuntu14.04下安装和&quot;激活&quot;Office2010ProPlus与Visio2010(15.11.20Updated)

    本人用Ubuntu的时候全然没有打游戏的欲望,故而能够更高效的工作. 尽管说LibreOffice.WPS等等有Ubuntu版本号,可是用着还是没有微软的Office顺手,故而折腾了一下怎样安装Off ...

  3. Sharepoint 2013 左右&quot;SPChange&quot;一个简短的引论

    于SharePoint于,我们经常需要获得这些更改项目,竟api为我们提供SPChange物.下列,在通过我们的目录资料这一目标. 1.创建测试列表,名字叫做"SPChangeItems&q ...

  4. 设置android:supportsRtl=&quot;true&quot;无效问题

     今天解bug时,遇到这样一个问题:   问题描写叙述:切换系统语言为阿拉伯文时,actionbar布局没有变为从右向左排列.   于是,我在Androidmanifest.xml文件里的 appli ...

  5. 都div在所有li的html()值被设置&quot;哈哈&quot;,当点击设置&quot;我被点击&quot;,其余的还是不点击设置“哈哈”

    <1> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://w ...

  6. u-boot: Error: Can&#39;t overwrite &quot;ethaddr&quot;

    When try to execute following command, It reports error as following: --->8--- U-Boot> setenv ...

  7. 11gR2 Database Services for &quot;Policy&quot; and &quot;Administrator&quot; Managed Databases (文件 ID 1481647.1)

    In this Document   _afrLoop=1459311711568804&id=1481647.1&displayIndex=6&_afrWindowMode= ...

  8. &quot;CoolReaper&quot; --酷派手机后门

    文章转自:http://drops.wooyun.org/tips/4342 注:译文未获得平底锅授权,纯属学习性质翻译 原文:https://www.paloaltonetworks.com/con ...

  9. JS 循环遍历JSON数据 分类: JS技术 JS JQuery 2010-12-01 13:56 43646人阅读 评论(5) 收藏 举报 jsonc JSON数据如:{&quot;options&quot;:&quot;[{

    JS 循环遍历JSON数据 分类: JS技术 JS JQuery2010-12-01 13:56 43646人阅读 评论(5) 收藏 举报 jsonc JSON数据如:{"options&q ...

  10. UVa 127 - &quot;Accordian&quot; Patience POJ 1214 链表题解

    UVa和POJ都有这道题. 不同的是UVa要求区分单复数,而POJ不要求. 使用STL做会比較简单,这里纯粹使用指针做了,很麻烦的指针操作,一不小心就错. 调试起来还是很费力的 本题理解起来也是挺费力 ...

随机推荐

  1. Android:数据存储之SQLite

    Android在运行时集成了SQLite , 所以每个Android应用程序都可以使用SQLite数据库. 我们通过SQLiteDatabase这个类的对象操作SQLite数据库,而且不需要身份验证. ...

  2. 转载:【译】Android: 自定义View

    简介 每天我们都会使用很多的应用程序,尽管他们有不同的约定,但大多数应用的设计是非常相似的.这就是为什么许多客户要求使用一些其他应用程序没有的设计,使得应用程序显得独特和不同. 如果功能布局要求非常定 ...

  3. Android AIDL-跨进程

    Android在设计理念上强调组件化,组件之间的依赖性很小.我们往往发一个Intent请求就可以启动另一个应用的Activity,或者一个你不知道在哪个进程的Service,或者可以注册一个广播,只要 ...

  4. Java API —— 递归

    1.方法定义中调用方法本身的现象 2.递归注意实现         1) 要有出口,否则就是死递归         2) 次数不能太多,否则就内存溢出         3) 构造方法不能递归使用 3. ...

  5. C#ShowCursor光标的显示与隐藏

      使用using System.Runtime.InteropServices; [DllImport("user32.dll" , EntryPoint = "Sho ...

  6. 将Ftp添加到资源管理器中直接使用

    在资源管理器中,右键,添加网络位置. 然后输入ftp的url ftp://server2008 使用匿名方式登录

  7. 8天学通MongoDB——第八天 驱动实践

    作为系列的最后一篇,得要说说C#驱动对mongodb的操作,目前驱动有两种:官方驱动和samus驱动,不过我个人还是喜欢后者, 因为提供了丰富的linq操作,相当方便. 官方驱动:https://gi ...

  8. MinGW GCC下sleep()函数问题

    在MinGW GCC下编译带sleep()函数的测试程序,不管是包含了unistd.h头文件,还是stdio.h.stdlib.h头文件,就是找不到该函数的定义!在linux下,sleep()函数的头 ...

  9. JAVA操作Excel 可配置,动态 生成复杂表头 复杂的中国式报表表头

    转载:开源社区http://www.oschina.net/code/snippet_1424099_49530?p=2代码] [Java]代码 该代码实现了Excel复杂表头的生成 基于sql se ...

  10. log4j配置webapp日志系统

    1.基础知识: Log4j的中文文档 (这是根据最新的log4j(jakarta-log4j-1.2.8)的开发包自带文档的manual翻译的) http://dev.csdn.net/develop ...