全局静态变量vs函数中的静态变量?

时间:2022-09-06 10:19:14

What's the diference between use:

使用之间有什么不同:

static Foo foo;
// ...
foo.func();

And:

和:

Foo& GetFoo(void) 
{
    static Foo foo;
    return foo;
}

// ...

GetFoo().func();

Which is better?

哪个更好?

2 个解决方案

#1


10  

The principal difference is when construction occurs. In the first case, it occurs sometime before main() begins. In the second case, it occurs during the first call to GetFoo().

主要区别在于施工时。在第一种情况下,它发生在main()开始之前的某个时间。在第二种情况下,它发生在第一次调用GetFoo()期间。

It is possible, in the first case, for code to (illegally) use foo prior to its initialization. That is not possible in the second case.

在第一种情况下,有可能在初始化之前(非法地)使用foo。在第二种情况下,这是不可能的。

#2


1  

A GetFoo is generally used when you don't want copies of your class/object. For example:

当您不想要类/对象的副本时,通常使用GetFoo。例如:

class Foo
{
private:
    Foo(){};
    ~Foo();
public:
    static Foo* GetFoo(void) 
    {
        static Foo foo;
        return &foo;
    }

    int singleobject;
};

You can externally access singleobject via Foo::GetFoo()->sinlgeobject. The private constructors and destructors avoid your class getting copies created.

您可以通过Foo :: GetFoo() - > sinlgeobject从外部访问singleobject。私有构造函数和析构函数可以避免您的类创建副本。

For the use of static Foo foo, you must have public constructors declared which means you are always accessing your class by it, but your class will also be able to get copies.

对于静态Foo foo的使用,您必须声明公共构造函数,这意味着您始终通过它访问您的类,但您的类也将能够获取副本。

#1


10  

The principal difference is when construction occurs. In the first case, it occurs sometime before main() begins. In the second case, it occurs during the first call to GetFoo().

主要区别在于施工时。在第一种情况下,它发生在main()开始之前的某个时间。在第二种情况下,它发生在第一次调用GetFoo()期间。

It is possible, in the first case, for code to (illegally) use foo prior to its initialization. That is not possible in the second case.

在第一种情况下,有可能在初始化之前(非法地)使用foo。在第二种情况下,这是不可能的。

#2


1  

A GetFoo is generally used when you don't want copies of your class/object. For example:

当您不想要类/对象的副本时,通常使用GetFoo。例如:

class Foo
{
private:
    Foo(){};
    ~Foo();
public:
    static Foo* GetFoo(void) 
    {
        static Foo foo;
        return &foo;
    }

    int singleobject;
};

You can externally access singleobject via Foo::GetFoo()->sinlgeobject. The private constructors and destructors avoid your class getting copies created.

您可以通过Foo :: GetFoo() - > sinlgeobject从外部访问singleobject。私有构造函数和析构函数可以避免您的类创建副本。

For the use of static Foo foo, you must have public constructors declared which means you are always accessing your class by it, but your class will also be able to get copies.

对于静态Foo foo的使用,您必须声明公共构造函数,这意味着您始终通过它访问您的类,但您的类也将能够获取副本。