如何实现对象的克隆?如何实现单例模式?

实现对对象的克隆

移动构造(移动语义实现的):通过移动语义实现移动构造,旧对象的资源的拥有权转移给新对象

拷贝构造 :通过旧对象初始化新对象,可能会存在浅拷贝和深拷贝的问题

赋值运算符:把一个对象的属性赋值给另一个对象,实现对前一个对象的拷贝

自定义一个clone方法:对于基类和派生类的层次结构,定义一个虚函数 clone(),在派生类中重写该函数,以确保多态克隆。

cpp 复制代码
#include <iostream>
#include <string>

class Base {
public:
    virtual ~Base() {}
    virtual Base* clone() const = 0;
    virtual void display() const = 0;
};


class Derived : public Base {
private:
    int value;
    std::string name;

public:
    Derived(int v = 0, const std::string& n = "") : value(v), name(n) {}

    // 实现克隆方法
    Base* clone() const override {
        return new Derived(*this);
    }

    void display() const override {
        std::cout << "Value: " << value << ", Name: " << name << std::endl;
    }
};


int main() {
    Derived obj1(42, "Derived Object");
    std::cout << "Original object: ";
    obj1.display();

    // 使用 clone 方法进行克隆
    Base* obj2 = obj1.clone();
    std::cout << "Cloned object: ";
    obj2->display();

    delete obj2;

    return 0;
}

使用模板和完美转发:使用模板函数进行克隆,通过完美转发将参数传递给对象的构造函数,实现通用的克隆机制。

完美转发:在 C++ 中,完美转发(Perfect Forwarding)是一种将参数以其原始的类型和值类别(左值或右值)传递给另一个函数的技术。它主要使用 std::forward 函数模板和转发引用(也称为万能引用,Forwarding Reference)来实现。

cpp 复制代码
#include <iostream>
#include <utility>

template <typename T, typename... Args>
T* clone(Args&&... args) {
    return new T(std::forward<Args>(args)...);
}


class SimpleClass {
private:
    int value;

public:
    SimpleClass(int v = 0) : value(v) {}

    void display() const {
        std::cout << "Value: " << value << std::endl;
    }
};


int main() {
    SimpleClass obj1(10);
    std::cout << "Original object: ";
    obj1.display();

    // 使用模板函数进行克隆
    SimpleClass* obj2 = clone<SimpleClass>(obj1);
    std::cout << "Cloned object: ";
    obj2->display();

    delete obj2;

    return 0;
}

如何实现单例模式?

懒汉式(线程不安全)

cpp 复制代码
#include <iostream>


class Singleton {
private:
    static Singleton* instance;
    Singleton() {}  // 构造函数私有,防止外部实例化

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }


    void display() const {
        std::cout << "This is a singleton instance." << std::endl;
    }
};


Singleton* Singleton::instance = nullptr;


int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    s1->display();
    s2->display();
    // 注意:没有释放内存,可能导致内存泄漏
    return 0;
}

懒汉式(线程安全,使用互斥锁)

cpp 复制代码
#include <iostream>
#include <mutex>


class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}  // 构造函数私有,防止外部实例化

public:
    static Singleton* getInstance() {
        std::lock_guard<std::mutex> lock(mtx);
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }


    void display() const {
        std::cout << "This is a singleton instance." << std::endl;
    }
};


Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;


int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    s1->display();
    s2->display();
    // 注意:没有释放内存,可能导致内存泄漏
    return 0;
}

饿汉式

cpp 复制代码
#include <iostream>


class Singleton {
private:
    static Singleton* instance;
    Singleton() {}  // 构造函数私有,防止外部实例化

public:
    static Singleton* getInstance() {
        return instance;
    }


    void display() const {
        std::cout << "This is a singleton instance." << std::endl;
    }
};


Singleton* Singleton::instance = new Singleton();


int main() {
    Singleton* s1 = Singleton::getInstance();
    Singleton* s2 = Singleton::getInstance();
    s1->display();
    s2->display();
    // 注意:没有释放内存,可能导致内存泄漏
    return 0;
}

Meyers' Singleton (C++11 及以后)

cpp 复制代码
#include <iostream>


class Singleton {
private:
    Singleton() {}  // 构造函数私有,防止外部实例化


public:
    static Singleton& getInstance() {
        static Singleton instance;
        return instance;
    }


    void display() const {
        std::cout << "This is a singleton instance." << std::endl;
    }
};


int main() {
    Singleton& s1 = Singleton::getInstance();
    Singleton& s2 = Singleton::getInstance();
    s1.display();
    s2.display();
    return 0;
}
相关推荐
xiaoye-duck27 分钟前
《C++ 项目:手写大模型接入 SDK》DeepSeek接口设计(下):流式响应实现和测试
开发语言·网络·c++·语言模型
旖旎夜光2 小时前
【C++ 基础入门】类和对象(上):封装、对象模型与 this 指针
开发语言·c++·笔记·学习
小超人诞生日记2 小时前
C++ 智能指针的使用及其原理详解
c++·算法
akinggw3 小时前
libagentcore - 一个基于c++的AI多agent系统升级到2.0版本
开发语言·jvm·c++
繁星蓝雨4 小时前
C++设计原理———多重继承(虚基类、菱形继承、委托、重命名、基类和成员初始化)
c++·委托·多重继承·mi·显式初始化列·虚基类·对象布局
旖旎夜光5 小时前
【C++ 基础入门】命名空间、输入输出、缺省参数与函数重载
开发语言·c++·笔记·学习
扶尔魔ocy6 小时前
【QT入门到晋级】用开源的自定义控件开发
c++·qt·自定义控件
akinggw7 小时前
libsherpacore - 基于 sherpa-onnx 的 C++ 语音交互静态库
c++·交互·语音识别
xiaoye-duck7 小时前
《C++ 项目:手写大模型接入 SDK》ChatGPT接口设计(中):全量响应实现和测试
网络·c++·语言模型·chatgpt
東隅已逝,桑榆非晚8 小时前
算法3.双指针法-快乐数
c++·笔记·学习·算法