不想允许“智能指针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轻量版有透视吗,wepoker买钻石有用吗(透视)透明挂教程(有挂攻略);...
透视有挂!wepoker有用吗... 透视有挂!wepoker有用吗,wepoker怎么发冤家牌(透视)2025新版(有挂攻略)1、让任何...
透视代打!wepoker能不能... 透视代打!wepoker能不能透视,wepoker辅助器是真的吗(透视)切实教程(有挂方法)暗藏猫腻...
透视插件!we poker辅助... 透视插件!we poker辅助器v3.3,we poker插件(透视)必备教程(有挂揭秘)1、超多福...
透视总结!wepoker免费辅... 透视总结!wepoker免费辅助器,wepoker脚本下载(透视)细节揭秘(有挂解密);1、上手简单...
透视科技!wepoker模拟器... 透视科技!wepoker模拟器哪个,wepoker私人定制透视(透视)解说技巧(有挂脚本)所有人都在...
透视系统!wepoker怎么发... 透视系统!wepoker怎么发冤家牌,wepoker新号好一点吗(透视)细节方法(有挂教程);1、点...
透视规律!wepoker分析,... 透视规律!wepoker分析,wepoker有辅助功能吗(透视)靠谱教程(有挂辅助)1、wepoke...
透视app!poker辅助器免... 透视app!poker辅助器免费安装,wepoker提高好牌率(透视)扑克教程(有挂方法)poker...
透视最新!wepoker黑侠破... 透视最新!wepoker黑侠破解,wepoker有机器人吗(透视)必胜教程(有挂工具);1、完成we...