gpt4 book ai didi

c++ - 如何正确创建单例对象并在 C++ 中使用它?

转载 作者:行者123 更新时间:2023-11-30 01:16:31 25 4
gpt4 key购买 nike

背景

我在 OOP 方面的大部分经验都来自 Objective-C。在该语言中,实例 方法之间有明显的区别。因此,在没有任何副作用的情况下使用单例相当容易。

C++ 中,我就没那么幸运了,我似乎无法避免创建不受我控制的对象。

代码

我有以下对象

class Window
{
private:
Window();
Window(Window const &windowCopy);
void operator=(Window const &windowRight);

public:
~Window();
static Window getSingleton();
};

这是.h。大多数实现只是我使用 cout 在调用 .h 中的每个方法时打印消息。 getSingleton() 方法除外。

Window Window::getSingleton()
{
static Window singleton;
return singleton;
}

这是我的主要内容

int main(int argc, char *argv[])
{
Window::getSingleton();
Window::getSingleton();

std::cout << "Stack is being removed" << std::endl;

return 0;
}

结果

运行后得到如下输出

Window created   -> 0x10c9bf0e0 // This is the static singleton
Window copied -> 0x7fff53242bb8 <- from 0x10c9bf0e0 // What is this?
Window destroyed -> 0x7fff53242bb8 // And what is it's scope?
Window copied -> 0x7fff53242bb0 <- from 0x10c9bf0e0
Window destroyed -> 0x7fff53242bb0
Stack is being removed
Window destroyed -> 0x10c9bf0e0

问题

出于某种原因,每当我调用单例方法时,都会出现一个新对象,并且单例会被分配给自身。为什么?我该如何更改它,以便在应用程序的整个持续时间内只有 一个 Window 对象?

最佳答案

您正在按值传递对象

Window Window::getSingleton()
{
static Window singleton;
return singleton;
}

您应该通过引用(或指向它的指针)返回它

Window& Window::getSingleton()
{
static Window singleton;
return singleton;
}

这通常是预期的行为 of the singleton pattern .

关于c++ - 如何正确创建单例对象并在 C++ 中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26448800/

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