Cocos2Dx中Singleton的正确实现方式

Correct way to implement Singleton in Cocos2Dx

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

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