简体   繁体   English

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

[英]global static variable vs static variable in function?

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? 哪个更好?

The principal difference is when construction occurs. 主要区别在于施工时。 In the first case, it occurs sometime before main() begins. 在第一种情况下,它发生在main()开始之前的某个时间。 In the second case, it occurs during the first call to GetFoo() . 在第二种情况下,它发生在第一次调用GetFoo()

It is possible, in the first case, for code to (illegally) use foo prior to its initialization. 在第一种情况下,有可能在初始化之前(非法地)使用foo That is not possible in the second case. 在第二种情况下,这是不可能的。

A GetFoo is generally used when you don't want copies of your class/object. 当您不想要类/对象的副本时,通常使用GetFoo For example: 例如:

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 . 您可以从外部访问, singleobject通过Foo::GetFoo()->sinlgeobject The private constructors and destructors avoid your class getting copies created. 私有构造函数和析构函数可以避免您的类创建副本。

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. 对于static Foo foo的使用,您必须声明公共构造函数,这意味着您始终通过它访问您的类,但您的类也将能够获取副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM