不想允许“智能指针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来创建智能指针对象,该函数可以访问智能指针的私有构造函数。同时,我们还禁用了拷贝构造函数和赋值操作符,以防止智能指针对象的拷贝和赋值。这样,就可以达到不允许直接创建智能指针对象的目的。

相关内容

热门资讯

专业透视!pokerworld... 专业透视!pokerworld修改器,微乐江苏小程序游戏破解下载,办法教程(详细教程)-哔哩哔哩1、...
详细透视!pokerworld... 详细透视!pokerworld辅助器,微乐自建房辅助工具官网,技法教程(有挂技巧)-哔哩哔哩亲,关键...
推荐透视!wepoker开脚本... 推荐透视!wepoker开脚本视频,微乐游戏竞技团辅助,指南书教程(有挂解密)-哔哩哔哩1、游戏颠覆...
开挂透视!aapoker辅助怎... 开挂透视!aapoker辅助怎么用,微乐小程序自建房辅助ios,攻略教程(有挂方略)-哔哩哔哩1、超...
曝光透视!wepoker如何设... 曝光透视!wepoker如何设置透视,微信小程序游戏破解器,攻略教程(确实有挂)-哔哩哔哩小薇(辅助...
曝光透视!epoker有透视吗... 曝光透视!epoker有透视吗,微乐手游脚本辅助,窍要教程(证实有挂)-哔哩哔哩1、epoker有透...
辅助透视!德州hhpoker脚... 辅助透视!德州hhpoker脚本,微乐自建房脚本下载,总结教程(果真有挂)-哔哩哔哩1、辅助透视!德...
普及透视!wepoker作弊方... 普及透视!wepoker作弊方法,微乐a3纸牌有脚本,模板教程(的确有挂)-哔哩哔哩亲,关键说明,w...
揭幕透视!pokerworld... 揭幕透视!pokerworld修改器,微乐小程序授权,机巧教程(有挂头条)-哔哩哔哩1、用户打开应用...
分享透视!wepoker-h5... 分享透视!wepoker-h5下载,微乐如何自己建脚本,机巧教程(有挂技巧)-哔哩哔哩1、点击下载安...