首页 > 其他分享 >如果在单例模式中返回share_ptr ???

如果在单例模式中返回share_ptr ???

时间:2024-10-12 16:34:57浏览次数:1  
标签:std Singleton share 单例 shared ptr 构造函数

背景:

接触到一个很有意思的题目:如果在单例模式中返回share_ptr ???

static std::shared_ptr<Singleton> getInstance() ;

 

分析:

这个问题的难点在于如果要实现单例,那么一定要把构造函数变成私有的,但是make_shared一定是调用的public的函数。

破题思路是:把构造函数变成public,但是通过别的手段限制外部调用。 同时又保证 getInstance可以调用到。

具体而言:定义一个私有的类成员,在构造函数中通过参数传递进来。

 

上代码:

#include <iostream>
#include <memory>
#include <mutex>

class Singleton {
private:
    struct privatenum {
        int num;
    }k;
public:
    // 获取单例实例的方法
    static std::shared_ptr<Singleton> getInstance() {
        // 使用双重检查锁定来确保线程安全
        static std::shared_ptr<Singleton> instance; // 未初始化
        if (!instance) {
            std::lock_guard<std::mutex> lock(mutex_); // 锁定以确保线程安全
            if (!instance) {
                privatenum k;
                instance = std::make_shared<Singleton>(k); // 使用make_shared创建实例
            }
        }
        return instance;
    }

    // 其他成员函数
    void showMessage() {
        std::cout << "Hello from Singleton!" << std::endl;
    }

  // 只要 k是私有的,那么就不能在外面调用。 Singleton(privatenum k) {}; private: // 私有化构造函数,避免外部实例化 // 禁用拷贝构造函数和赋值操作符 Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static std::mutex mutex_; // 互斥锁 }; // 定义静态成员变量 std::mutex Singleton::mutex_; int main() { // 使用单例 std::shared_ptr<Singleton> singleton1 = Singleton::getInstance(); singleton1->showMessage(); std::shared_ptr<Singleton> singleton2 = Singleton::getInstance(); singleton2->showMessage(); // 检查两个实例是否相同 std::cout << "Instances are equal: " << (singleton1 == singleton2) << std::endl; return 0; }

 

标签:std,Singleton,share,单例,shared,ptr,构造函数
From: https://www.cnblogs.com/xcywt/p/18460813

相关文章

  • java单例模式懒汉式 双重校验 关键字volatile
    Volatile关键字的作用Volatile关键字的作用主要有如下两个:1.线程的可见性:当一个线程修改一个共享变量时,另外一个线程能读到这个修改的值。2.顺序一致性:禁止指令重排序。不保证原子性一、线程可见性我们先通过一个例子来看看线程的可见性:publicclassVolatileTest{ ......
  • C++ 读写锁 shared_mutex
    C++17新增了std::shared_mutex,通过shared_mutex可以实现读写锁的功能, 参考网址:https://zh.cppreference.com/w/cpp/thread/shared_mutexshared_mutex可以同时支持多个线程对共享资源同时读,但是只支持一个线程对同一共享资源进行写操作。shared_mutex支持共享锁和独......
  • Spring事务管理与AOP代理的原理,默认的单例对象和代理对象销毁的时机
    Spring的事务管理是使用AOP(面向切面编程)代理的原理来实现的。Spring事务管理与AOP代理原理AOP代理的作用:在Spring中,AOP代理用于在目标对象的方法执行前后注入自定义的逻辑,这些逻辑通常与业务逻辑无关,但需要在业务逻辑执行时同步执行,如事务管理、日志记录、性能检测等。通过......
  • import mindnlp报错:OSError: cannot load library ‘libsndfile.so‘: libsndfile.so:
    在启智平台AI调试环境下,安装mindnlp后,importmindnlp报错。安装mindnlp命令:#安装mindnlp的daily包,待正式发布后可改为直接安装mindnlp包!pipinstallhttps://mindspore-courses.obs.cn-north-4.myhuaweicloud.com/mindnlp/mindnlp-0.4.0-py3-none-any.whl-ihttps://pypi.......
  • nullopt&&nullptr
    std::nullopt是C++17中引入的一个特殊值,用来表示std::optional类型中的“无值”状态。它用于显式地表示某个std::optional对象不包含有效值,而不是用默认构造函数或其他不明确的方式表示。std::nullopt的使用std::nullopt是一个常量,可以直接赋值给std::optional类型的......
  • Spring Boot 3 配置 Redis 兼容单例和集群
    配置项SpringBoot3.x的redis配置和SpringBoot2.x是不一样的,路径多了一个dataspring:...data:redis:host:@redis.host@port:@redis.port@password:@redis.password@database:@redis.database@兼容单例和集群的配置开发......
  • why do we need 'select…for share' instead of a simple 'select'
    (Fromchatgpt)AsimpleSELECTqueryinPostgreSQLoperatesundertheMVCC(Multi-VersionConcurrencyControl)model,whichallowsittoreaddatawithoutlockingtherows.Thismeansitcanseeasnapshotofthedataatthestartofthetransaction,rega......
  • 对UVM添加超时前的打印信息+AXI低功耗接口+process的await语句+对象当成参数+sv的单例
    对UVM添加超时前的打印信息首先获取到UVM的超时值,然后手动设定\$time的比较和while延时循环,当超出时间后,打印特殊的debug信息。$time<set_time,则进行循环。uvm_cmdline_processorclp;clp=uvm_cmdline_processor::get_inst();stringtimeout_settings[$];stringtimeout......
  • std::make_shared
    std::make_shared是C++11引入的一个标准库函数,用于创建一个std::shared_ptr,并在堆上分配所需的对象。它的功能是将对象的创建和shared_ptr的初始化合并在一起,提高了效率和安全性。使用方法:autoptr=std::make_shared<T>(args...);T:共享指针所管理的对象的类型。a......
  • Python 单例模式:确保类的实例唯一
    在Python编程中,设计模式是解决特定问题的可复用的解决方案。单例模式是一种创建型设计模式,它在许多场景下都有着重要的应用。本文将深入探讨Python中的单例模式,包括其定义、实现方式、应用场景以及需要注意的要点等。一、单例模式的定义单例模式是一种设计模式,它确保......