C++11 之 " = delete "

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 函数时,则编译时就会报错。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值