不想允许“智能指针smart<int> o1(new int())”。
创始人
2025-01-10 07:30:08
0

在C++中,我们可以通过私有化智能指针的构造函数和拷贝构造函数,以及将智能指针类声明为友元类来阻止直接创建智能指针对象。下面是一个示例代码:

#include 

template
class smart_ptr {
private:
    T* ptr;
    smart_ptr(T* p) : ptr(p) {} // 私有构造函数

public:
    smart_ptr() : ptr(nullptr) {} // 默认构造函数
    ~smart_ptr() { delete ptr; } // 析构函数

    // 友元声明
    template
    friend smart_ptr make_smart_ptr(U* p);

    // 禁用拷贝构造函数
    smart_ptr(const smart_ptr& other) = delete;

    // 禁用赋值操作符
    smart_ptr& operator=(const smart_ptr& other) = delete;

    T* operator->() const { return ptr; }
};

template
smart_ptr make_smart_ptr(T* p) {
    return smart_ptr(p);
}

int main() {
    smart_ptr o1 = make_smart_ptr(new int()); // 编译错误,禁止直接创建智能指针对象

    return 0;
}

在上面的代码中,我们将智能指针的构造函数声明为私有,这样就不能直接创建智能指针对象。通过友元函数make_smart_ptr来创建智能指针对象,该函数可以访问智能指针的私有构造函数。同时,我们还禁用了拷贝构造函数和赋值操作符,以防止智能指针对象的拷贝和赋值。这样,就可以达到不允许直接创建智能指针对象的目的。

相关内容

热门资讯

总结透视!购买wepoker模... 总结透视!购买wepoker模拟器,pokemmo手机版透视脚本,步骤教程(详细教程)-哔哩哔哩1、...
详情透视!pokemmo辅助脚... 详情透视!pokemmo辅助脚本!真是存在有辅助教程(有挂秘籍)-哔哩哔哩1、不需要AI权限,帮助你...
总结透视!aapoker发牌逻... 总结透视!aapoker发牌逻辑,hhpoker透视脚本下载,窍门教程(真实有挂)-哔哩哔哩1)hh...
了解透视!xpoker辅助助手... 了解透视!xpoker辅助助手!都是真的有辅助攻略(有挂总结)-哔哩哔哩1、完成xpoker辅助助手...
曝光透视!黑侠破解wepoke... 曝光透视!黑侠破解wepoker,xpoker辅助怎么用,项目教程(有挂方略)-哔哩哔哩1、xpok...
专业透视!wepoker轻量版... 专业透视!wepoker轻量版透视方法,wepoker透视脚本免费下载,绝活儿教程(有挂教学)-哔哩...
总结透视!约局吧开挂神器是真的... 总结透视!约局吧开挂神器是真的吗!一直是有辅助软件(确实有挂)-哔哩哔哩;1、约局吧开挂神器是真的吗...
有挂透视!hhpoker到底可... 有挂透视!hhpoker到底可以作必弊吗,aa poker辅助包,项目教程(真的有挂)-哔哩哔哩1、...
普及透视!pokemmo免费脚... 普及透视!pokemmo免费脚本!总是一直总是有辅助教程(有挂秘笈)-哔哩哔哩所有人都在同一条线上,...
有挂透视!wepoker辅助透... 有挂透视!wepoker辅助透视,aapoker辅助怎么用,诀窍教程(有挂规律)-哔哩哔哩1)aap...