muduo__noncopyable禁止拷贝

本文探讨了C++中`noncopyable`类的设计,它通过删除拷贝构造函数和赋值操作符,防止类实例的无意复制。子类classA继承noncopyable,展示了在尝试调用拷贝构造和赋值时的错误行为。重点在于理解类的生命周期管理和防止滥用复制。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;
 
class noncopyable
{
public:
    noncopyable(const noncopyable&) = delete;
    void operator=(const noncopyable&) = delete;

//构造函数是protected的,因为这个类不需要被实例化,但是又需要能让子类实例化
protected:
    noncopyable() = default;
    ~noncopyable() = default;
};

//子类继承noncopyable类,调用拷贝构造函数时,找不到父类的拷贝构造函数就会报错
class classA : public noncopyable
{
public:
    classA() {};
    classA(int i) { a = i; };

public:
    int a;
};

int main()
{
    classA a1;
    classA a2(1);

    //classA a3 = a1;         //error
    //classA a4(a1);          //error
    system("pause");
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值