随笔 - 192,  文章 - 0,  评论 - 2,  阅读 - 25万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

 


编译器默认为一个类生成的默认函数

  1. 默认构造函数
  2. 默认析构函数
  3. 默认拷贝构造函数
  4. 默认赋值函数
  5. 移动构造函数
  6. 移动拷贝函数
复制代码
class DataOnly {
public:
    DataOnly ()                  // default constructor
    ~DataOnly ()                 // destructor

    DataOnly (const DataOnly & rhs)              // copy constructor
    DataOnly & operator=(const DataOnly & rhs)    // copy assignment operator

    DataOnly (const DataOnly && rhs)         // C++11, move constructor
    DataOnly & operator=(DataOnly && rhs)    // C++11, move assignment operator
};
复制代码

=delete

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

假如上面的几个函数中,不想使用其中某个,可以将其定义为private,或者使用=delete

复制代码
#include <iostream>
using namespace std;

class DataOnly {
public:
    DataOnly () {}
    ~DataOnly () {}

    DataOnly (const DataOnly & rhs) = delete; //禁止使用该函数
    DataOnly & operator=(const DataOnly & rhs) = delete; //禁止使用该函数

    DataOnly (const DataOnly && rhs) {}
    DataOnly & operator=(DataOnly && rhs) {}
};

int main(int argc, char *argv[]) {
    DataOnly data1;
    DataOnly data2(data1); // error: call to deleted constructor of 'DataOnly'
    DataOnly data3 = data1; // error: call to deleted constructor of 'DataOnly'
    return 0;
}
复制代码

2. 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;
}
复制代码

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

例如:Widget 类中声明了一个模板函数,当进行模板特化时,要求禁止参数为 void* 的函数调用。 
1. 按照私有不实现思路,应该是将特例化的函数声明为私有型,如下:

复制代码
#include <iostream>
using namespace std;

class Widget {
public:
    template<typename T>
    void ProcessPointer(T* ptr) { 
        cout << typeid (T).name() << endl;
    }
private:        
    void ProcessPointer(void*) { 
        cout << "void" << endl;
    }
};

int main(int argc, char *argv[]) {
    Widget w;
    int* ip = NULL;
    w.ProcessPointer(ip);

    void* vp = NULL;
    w.ProcessPointer(vp); //error: 'ProcessPointer' is a private member of 'Widget' w.ProcessPointer(vp);
    return 0;
}
复制代码
  1. =delete直接添加在后面就可以解决这个问题

= default

在程序员重载了自己上面提到的C++编译器默认生成的函数之后,C++编译器将不在生成这些函数的默认形式。 
但是C++允许我们使用=default来要求编译器生成一个默认函数,如

struct Point {
    Point()=default;
    Point(int _x, int _y) : x(_x), y(_y) {}
    int x = 0;
    int y = 0;
}

这样相当于无参的构造函数也是可以使用的

本文转自:https://blog.csdn.net/lmb1612977696/article/details/80035487

posted on   Malphite  阅读(2841)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示