在C ++中没有静态构造函数的理由是什么? [英] What is the rationale for not having static constructor in C++?

查看:272
本文介绍了在C ++中没有静态构造函数的理由是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中没有静态构造函数的原因是什么?

What is the rationale for not having static constructor in C++?

如果允许,我们将初始化其中的所有静态成员,非常有条理的方式,如:

If it were allowed, we would be initializing all the static members in it, at one place in a very organized way, as:

//illegal C++
class sample
{
public:

    static int some_integer;
    static std::vector<std::string> strings;

    //illegal constructor!
    static sample()
    {
       some_integer = 100;
       strings.push_back("stack");
       strings.push_back("overflow");
    }
};



在缺少静态构造函数的情况下,很难有静态向量,如上图所示。静态构造函数优雅地解决了这个问题。我们可以以非常有条理的方式初始化静态成员。

In the absense of static constructor, it's very difficult to have static vector, and populate it with values, as shown above. static constructor elegantly solves this problem. We could initialize static members in a very organized way.

那么为什么'C ++没有静态构造函数?毕竟,其他语言(例如C#)都有静态构造函数!

So why doesn't' C++ have static constructor? After all, other languages (for example, C#) has static constructor!

推荐答案

使用静态初始化顺序问题作为借口不向这个语言引入这个特性是并且总是一个现状的问题 - 它没有介绍,因为它没有介绍,人们一直认为初始化顺序是不介绍它的原因,即使顺序问题一个简单和非常直接的解决方案。

Using the static initialization order problem as an excuse to not introducing this feature to the language is and always has been a matter of status quo - it wasn't introduced because it wasn't introduced and people keep thinking that initialization order was a reason not to introduce it, even if the order problem has a simple and very straightforward solution.

初始化顺序,如果人们真的想解决这个问题,他们会有一个非常简单和直接的解决方案:

Initialization order, if people would have really wanted to tackle the problem, they would have had a very simple and straightforward solution:

//called before main()

int static_main() {

ClassFoo();
ClassBar();

}

以及适当的声明:

class ClassFoo {
 static int y;
  ClassFoo() {
   y = 1;
  }
}

class ClassBar {
  static int x;
  ClassBar() {
   x = ClassFoo::y+1;
  }
}

所以答案是,没有理由在那里,至少没有技术。

So the answer is, there is no reason it isn't there, at least not a technical one.

这篇关于在C ++中没有静态构造函数的理由是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆