c++ - Cocos2Dx中Singleton的正确实现方式

标签 c++ c++11 singleton cocos2d-x

目前我正在使用这种方法:

class Singleton {
public:
  static Singleton &getInstance()   {
    static Singleton *instance = new Singleton();
    return *instance;
  }
void getData();

private:
  Singleton() {}
};

这样我就可以使用Singleton编写的方法:

Singleton::getInstance.getData();

这似乎是阅读大量 C++11 教程的正确方法。 但是通过阅读 cocos Director 单例代码(还有 FileUtils 等),我看到 Cocos 使用了另一种方法:

class Singleton {
public:
  static Singleton *getInstance()   {
    instance = new Singleton();
    return instance;
  }
void getData();

private:
  Singleton() {}
  static Singleton *instance;
};

用这种方法我必须写:

Singleton::getInstance->getData();

因为指针 *getInstance 而不是引用 &getInstance

我觉得差别很大,但我不知道一种方式是否正确,另一种方式是否正确。

请帮我理清这个概念。

最佳答案

在我看来,最好的单例是作为值类型呈现的,具有隐藏的单例实现。

这意味着您可以像传递任何其他对象一样传递单例。

这反过来意味着,如果您稍后改变主意,而单例实际上需要是一个普通对象,则无需更改任何代码。

这也意味着您的单例对象可以参与 ADL 和标签分发。

例如:

#include <iostream>

// only this goes in the header file
struct my_thing
{
    // public interface
    int do_or_get_something(int arg);

private:
    struct impl;
    static impl& get_impl();

};

// this goes in the cpp file
struct my_thing::impl
{
    int do_or_get_something(int arg)
    {
        // for demo purposes
        return counter += arg;
    }

    int counter = 0;  // for demo purposes
};

my_thing::impl& my_thing::get_impl()
{
    // create first time code flows over it - c++ standard
    // thread safe in c++11 - guarantee
    static impl instance {};
    return instance;
}

// implement public interface in terms of private impl
int my_thing::do_or_get_something(int arg)
{
    return get_impl().do_or_get_something(arg);
}

// test the concept
int main()
{
    auto one_thing = my_thing();
    std::cout << one_thing.do_or_get_something(5) << std::endl;
    std::cout << one_thing.do_or_get_something(5) << std::endl;

    auto another_thing_but_really_same = my_thing();
    std::cout << another_thing_but_really_same.do_or_get_something(5) << std::endl;

    std::cout << my_thing().do_or_get_something(5) << std::endl;
    std::cout << one_thing.do_or_get_something(5) << std::endl;

}

预期输出:

5
10
15
20
25

关于c++ - Cocos2Dx中Singleton的正确实现方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36311163/

相关文章:

c++ - std::set 和 std::unordered_set 如何使用 emplace() 就地构造元素?

c++11 - 转发转发引用的单个成员

java - 隐藏一个类对其他类的可见性

java - 为什么我的@singleton 不起作用?

c++11 struct初始化编译错误

c++ - 如何在 Windows 中创建线程安全的单例模式?

c++ - 使用 sed 命令换行字符串

c++ - 为什么不能在派生类的构造函数初始化列表中初始化基类的数据成员?

c++ - AppVeyor 上带有 g-tests 的 Visual Studio 解决方案

c++ - 重定义数据成员时类的实现