gpt4 book ai didi

C++单例模式

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:57 26 4
gpt4 key购买 nike

考虑以下来自 yolinux 的单例模式设计(http://www.yolinux.com/TUTORIALS/C++Singleton.html)

#include <string>

class Logger{
public:
static Logger* Instance();
bool openLogFile(std::string logFile);
void writeToLogFile();
bool closeLogFile();

private:
Logger(){}; // Private so that it can not be called
Logger(Logger const&){}; // copy constructor is private
Logger& operator=(Logger const&){}; // assignment operator is private
static Logger* m_pInstance;
};

有人能解释一下为什么这里需要 Logger(Logger const&){};Logger& operator=(Logger const&){}; 吗?
提前致谢。

最佳答案

如果您强制复制构造函数和赋值运算符为私有(private),那么您将无法编译两个 Logger 对象的赋值。

这将导致链接器错误,这不是显式消息。这些方法是默认生成的,所以你必须强制它们是私有(private)的

在 C++11 中,他们使用删除的方法来获得更清晰的信息

   Logger(Logger const&)=delete;             // copy constructor does not exist
Logger& operator=(Logger const&)=delete; // assignment operator does not exist

删除不是强制性的,单例在没有此功能的情况下也能正常工作,因此如果您的编译器不支持此功能,您只需将其设为私有(private)即可。此功能会给出明确的错误消息,但不会影响单例本身的行为。

有关删除功能的更多信息,您可以在这里查看:

Meaning of = delete after function declaration

您还可以通过将析构函数设为私有(private)来防止对象被销毁。

What is the use of having destructor as private?

关于C++单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23194585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com