- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!