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

相关内容

热门资讯

透视线上"wepok... 透视线上"wepoker透视最简单三个步骤"详细辅助总结教程(高级辅助透明);wepoker透视最简...
透视透视挂"wepo... 透视透视挂"wepoker辅助器最新版本更新内容"详细辅助教你教程(内置辅助攻略),支持语音通讯、好...
透视辅助"竞技联盟透... 透视辅助"竞技联盟透视插件"详细辅助曝光教程(黑侠辅助器正版下载方法);人气非常高,ai更新快且高清...
透视好牌"aapok... 透视好牌"aapoker透视插件"详细辅助必赢教程(辅助器下载透视);实战中需综合运用上述技巧,并根...
透视挂透视"xpok... 透视挂透视"xpoker辅助神器"详细辅助高科技教程(免费脚本咨询教程)1、不需要AI权限,帮助你快...
透视私人局"德普之星... 1、透视私人局"德普之星辅助器"详细辅助揭秘教程(透视脚本是有挂方法)2、进入游戏-大厅左侧-新手福...
透视插件"wepok... 透视插件"wepoker作弊视频"详细辅助高科技教程(的辅助器技巧);实战中需综合运用上述技巧,并根...
透视安卓版"wepo... 透视安卓版"wepoker透视是真的吗"详细辅助科技教程(脚本透视);小薇(透视辅助)致您一封信;亲...
透视app"wepo... 透视app"wepoker免费脚本咨询"详细辅助系统教程(手机助手攻略);小薇(透视辅助)致您一封信...
透视能赢"wpk辅助... 透视能赢"wpk辅助插件"详细辅助AA德州教程(智能辅助插件技巧);1分钟了解详细教程(微信 136...