文章目录
代码
cpp
// GPIOManager.h
#ifndef GPIOMANAGER_H
#define GPIOMANAGER_H
#include <string>
#include <mutex>
#include <thread>
#include <chrono>
#include <atomic>
class GPIOManager
{
public:
static GPIOManager &getInstance();
~GPIOManager();
void setHigh();
void setLow();
int readValue();
int setHighThenLow(int delaySeconds, std::string &errorMsg);
private:
GPIOManager(); // 构造函数私有化
GPIOManager(const GPIOManager &) = delete;
GPIOManager &operator=(const GPIOManager &) = delete;
int gpioNumber = 438; // GPIO 编号
std::string gpioAlias = "PQ.03"; // GPIO 别名
std::string basePath;
std::string pinPath;
std::mutex gpioMutex; // 互斥锁
std::atomic<bool> isRunning; // 用于跟踪setHighThenLow是否正在执行
void initialize(); // 私有方法
void executeCommand(const std::string &cmd);
};
#endif // GPIOMANAGER_H
#if 0 // 使用方法
void someFunction() {
auto& gpio = GPIOManager::getInstance();
gpio.setHigh(); // 设置高电平
gpio.setLow(); // 设置低电平
}
#endif
其中有:
cpp
private:
GPIOManager(const GPIOManager &) = delete;
GPIOManager &operator=(const GPIOManager &) = delete;
解读
GPIOManager.h
头文件中,下面两行代码:
cpp
GPIOManager(const GPIOManager &) = delete;
GPIOManager &operator=(const GPIOManager &) = delete;
这些语句的作用是禁止拷贝和赋值操作对GPIOManager
类的对象。这是一种常见的做法,特别是在设计单例模式的类时。
解释
-
禁止拷贝构造函数 (
GPIOManager(const GPIOManager &) = delete
) :这行代码意味着你不能使用拷贝构造函数来创建一个
GPIOManager
的新实例,如下所示的操作是不允许的:cppGPIOManager a; GPIOManager b = a; // 编译错误,因为拷贝构造函数被删除
-
禁止赋值操作 (
GPIOManager &operator=(const GPIOManager &) = delete
) :这行代码阻止了将一个
GPIOManager
对象赋值给另一个现有的对象。例如,以下操作将引发编译时错误:cppGPIOManager a; GPIOManager b; b = a; // 编译错误,因为赋值操作符被删除
目的和优点
- 单例模式保护 :
GPIOManager
类设计为单例,这意味着整个程序的运行过程中只能有一个GPIOManager
的实例。禁止拷贝和赋值是保护这一单例实例不被无意复制或替换的一种手段。 - 避免资源复制问题:如果类管理如文件描述符或网络连接等外部资源,不当的拷贝可能导致资源管理混乱,如资源泄漏或意外的副作用(例如,两个对象试图关闭同一资源)。
- 线程安全:在多线程环境中,意外的拷贝可能导致竞态条件或数据一致性问题。通过删除拷贝和赋值操作符,你可以减少这种风险。
总的来说,这种做法是对单例设计模式的一个强化,确保了类的全局控制和资源管理的安全性。
ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ
ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ ᅟᅠ