C++11 关于 "=delete"

=delete

1. 禁止使用编译器默认生成的函数

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; 
};

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

#include <iostream>
using namespace std;

class DataOnly {
public:
    void fun(int a) {}
    void fun(float a) = delete;
};

int main(int argc, char *argv[]) {
    DataOnly data1;
    data1.fun(1); // OK
    data1.fun(0.5); // error: call to member function 'fun' is ambiguous
    return 0;
}

 

posted @ 2021-02-24 11:37  玥茹苟  阅读(181)  评论(0编辑  收藏  举报