自由函数vs单例vs静态类成员

时间:2019-01-30 10:56:38

标签: c++ static singleton

我继承了一些遗留代码,其中包含许多全局变量以及使用它们的许多全局函数。

我打算将代码重构为更简洁的代码,但是我看到了4种处理方式(下面以简化形式列出),并且我不了解每种方式的优缺点。

任何人都可以帮助我获得更清晰的照片吗?


可能性A(免费函数和变量):

// Basically it's still global functions and variables
//  but now the global namespace isn't polluted
//  and the variables are only accessible from onefile
namespace functionality
{
    namespace
    {
        int x = 0;
        double y = 0.;
    }

    int f()
    {
        return doStuff(x,y);
    }

    double g()
    {
        return doOtherStuff(x,y);
    }
}

// Called like this
auto val = functionality::f();
auto otherVal = functionality::g();

可能性B(具有静态成员的类):

class Functionality
{
private:
    static int x = 0;
    static double y = 0.;

public:
    static int f()
    {
        return doStuff(x,y);
    }

    static double g()
    {
        doOtherStuff(x,y);
    }
};

// Called like this
auto val = Functionality::f();
auto otherVal = Functionality::g();

可能性C(单例):

class Functionality
{
private:
    int x = 0;
    double y = 0.;
    Functionality()
    {}

public:
    static Functionality& getSingleton()
    {
        static Functionality singleton;
        return singleton;
    }

    int f()
    {
        return doStuff(x,y);
    }

    double g()
    {
        doOtherStuff(x,y);
    }
};

// Called like this
auto val = Functionality::getSingleton.f();
auto otherVal = Functionality::getSingleton.g();

可能性D(B和C的混合):

class Functionality
{
private:
    int x = 0;
    double y = 0.;
    Functionality()
    {}

    static Functionality& getSingleton()
    {
        static Functionality singleton;
        return singleton;
    }

    int f_impl()
    {
        return doStuff(x,y);
    }

    double g_impl()
    {
        doOtherStuff(x,y);
    }


public:
    static int f()
    {
        return getSingleton.f();
    }

    static double g()
    {
        return getSingleton.g();
    }
};

// Called like this
auto val = Functionality::f();
auto otherVal = Functionality::g();

那么,每个优点和缺点是什么?尤其是A,B和D之间是否存在实际差异?

0 个答案:

没有答案