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 之 &quot; = delete &quot;的更多相关文章

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

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

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

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

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

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

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

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

  5. 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 ...

  6. 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= ...

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

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

  8. 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 ...

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

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

随机推荐

  1. jdbc框架 commons-dbutils+google guice+servlet 实现一个例子

    最近闲着无聊,于是看了一下jdbc框架 commons-dbutils与注入google guice. 我就简单的封装了一下代码,效率还是可以的.... jdbc+google guice+servl ...

  2. Linux系统时间与RTC时间【转】

    http://bbs.chinaunix.net/forum.php?mod=viewthread&tid=3637782 Linux的RTC驱动相对还是比较简单的,可以将它作为一个普通的字符 ...

  3. Virtualbox: Shared directory- “unknown filesystem type vboxsf”

    1. "设置”中,"共享文件夹”,把要共享的文件夹添加上. 2. 然后打开系统,找到“安装增强功能”,这时桌面上多了一个光盘或者看/media/下面是不是已经文件了,虽然这个时候可 ...

  4. Spring 注解@Transactional

    Spring事务的传播行为 在service类前加上@Transactional,声明这个service所有方法需要事务管理.每一个业务方法开始时都会打开一个事务. Spring默认情况下会对运行期例 ...

  5. AIX 内存使用情况

    cat > WHAT_EVER_YOU_WANT.sh#!/usr/bin/ksh#memory calculatorum=`svmon -G | head -2|tail -1| awk {' ...

  6. [HDOJ1171]Big Event in HDU(01背包)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1171 许多有价值的物品,有重复.问如何将他们分成两堆,使两堆价值之差最小. 对价值求和,转换成01背包 ...

  7. Python自带包建立简单web服务器

    在DOS里cd到准备做服务器根目录的路径下,输入命令: python -m Web服务器模块 [端口号,默认8000] 例如: python -m SimpleHTTPServer 8080 然后就可 ...

  8. CFileDialog使用总结

    http://blog.csdn.net/tianhai110/article/details/2055149 CFileDialog经常用,但经常忘,现归纳整理下,方便今后查询. 例子: CFile ...

  9. 在单机Hadoop上面增加Slave

    之前的文章已经介绍了搭建单机Hadoop, HBase, Hive, Spark的方式:link 现在希望在单机的基础上,加一个slave. 首先需要加上信任关系,加信任关系的方式,见前一篇文章:li ...

  10. Toast报错 android.content.res.Resources$NotFoundException

    Toast.makeText(getActivity(), String.valueOf(position), Toast.LENGTH_SHORT)                         ...