1  缺省函数

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

class DataOnly {
private:
    std::string  strName;  // member data
    int         iData;
};

1.1  特殊成员函数

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

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

#include <iostream>

class DateOnly
{
private:
    std::string strName;
    int iDate;
public:
    DateOnly();
    DateOnly(std::string _str, int _iDate);
    ~DateOnly();

    DateOnly(const DateOnly& rhs);
    DateOnly& operator=(const DateOnly& rhs);

    DateOnly(const DateOnly&& rhs);
    DateOnly& operator=(const DateOnly&& rhs);
};

DateOnly::DateOnly(std::string _str, int _iDate) :strName(_str), iDate(_iDate){}

DateOnly::DateOnly(const DateOnly& rhs)
{
    strName = rhs.strName;
    iDate = rhs.iDate;
}

DateOnly& DateOnly::operator=(const DateOnly& rhs)
{
    this->strName = rhs.strName;
    this->iDate = rhs.iDate;
    return *this;
}

1.2  两个实现形式

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

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

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

 
DataOnly& DataOnly::operator=(const DataOnly &rhs)
{
    strName = rhs.strName;    // calls the string::operator=
    iData = rhs.iData;        // uses the built-in int assignment

    return *this;        // return a reference to this object
}
 

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

2  禁止缺省函数

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

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

class LeafFromTree{ ... };

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

LeafFromTree  leaf1;
LeafFromTree  leaf2;
LeafFromTree  Leaf3(Leaf1);     // attempt to copy Leaf1 — should not compile!
Leaf1 = Leaf2;                  // attempt to copy Leaf2 — should not compile!

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

2.1  私有+不实现

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

class LeafFromTree{
private:
    LeafFromTree( const LeafFromTree& );           // not defined
    LeafFromTree & operator=( const LeafFromTree& );    // not defined
};

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

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

 
class Uncopyable {
protected:            
    Uncopyable() {}    // allow construction and destruction of derived objects...
    ~Uncopyable() {}
private:
    Uncopyable(const Uncopyable&);  // ...but prevent copying
    Uncopyable& operator=(const Uncopyable&);
};
 

而 LeafFromTree 则私有继承自 Uncopyable 基类

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

2.2  delete 关键字

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

 
class LeafFromTree{
public:
  LeafFromTree() = default;  ~LeafFromTree() = default;

  LeafFromTree( const LeafFromTree& ) = delete;  // mark copy ctor or copy assignment operator as deleted functions
  LeafFromTree & operator=( const LeafFromTree &) = delete; };
 

3  delete 的扩展

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

3.1  函数重载

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

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

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

if (isLucky('a')) …     // error !    call to deleted function
if (isLucky(true)) …    // error !
if (isLucky(3.5)) …     // error !

3.2  模板特化

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

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

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

 
class Widget {
public:
    template<typename T>
    void processPointer(T* ptr) { … }
private:
    template<>
    void processPointer<void>(void*);    // error!
};
 

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

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

 
class Widget {
public:
    template<typename T>
    void processPointer(T* ptr) { … }
};

template<>
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. Linux suse x86_64 环境上部署Hadoop启动失败原因分析

    一.问题症状: 在安装hadoop的时候报类似如下的错误: # A fatal error has beendetected by the Java Runtime Environment: # #  ...

  2. linux c 生成uuid

    /********方法一**********/#include <stdio.h> #include <stdlib.h> #include <string.h> ...

  3. [原]poj-1611-The Suspects(水并查集)

    题目链接:http://poj.org/problem?id=1611 题意:输入n个人,m个组.初始化0为疑似病例.输入m个小组,每组中只要有一个疑似病例,整组人都是疑似病例.相同的成员可以在不同的 ...

  4. hadoop hadoop-0.20.2-cdh3u4升级

    [hadoop@lab02 ~]$ uname -aLinux lab02 2.6.18-194.el5 #1 SMP Tue Mar 16 21:52:39 EDT 2010 x86_64 x86_ ...

  5. matlab函数集锦

    matlab函数集锦 matlab函数集锦ISFINITE(X), ISINF(X), or ISNAN(X)pwd 当前目录eval 执行matlab函数CONV2(  ,'same')  卷积F  ...

  6. win7下搭建opengles2.0编程环境

    原帖地址:http://sixgod.org/archives/72   1.下载AMD的OpenGL ES2.0的模拟器,地址: http://www.opengles-book.com/ESEmu ...

  7. hdu1050(贪心)

    囧 . 想了好久,一开始想的是一个连通图怎样用黑白两色染色,想了各种算法发现都不好做,然后灵机一动这不是网路流吗,然后想怎么建图,如果转换成网络流这题就好做了,建图加个二分应该就可以解决了,最后又发现 ...

  8. 单点登录系统构建之一——基础知识(Kerberous/SAML)

    http://web.mit.edu/kerberos/ Kerberos Kerberous是一个网络身份验证协议,它被设计为客户端/服务器提供基于密钥的强加密机制.该协议最初由MIT实现并被广泛商 ...

  9. Home Server

    今天分享一个作品--HomeServer,一个基于云存储理念的集家庭数据存储.共享.管理及远程访问为一体的家用存储设备.通俗的讲,就是一个家庭数据银行,为家庭的数据提供专业.安全.便捷.持久.全天候的 ...

  10. jquery仿天猫商城左侧导航菜单

    之前看到有博友写了一个仿天猫商城左侧导航菜单,可惜不提供免费下载,也没有代码.以前自己也写过类似的效果,只是都是一小块一小块的,现在重新拼凑.我将一步一步的实现拼凑过程,希望对你有所帮助. Demo在 ...