简体   繁体   English

静态本地的C与C ++初始化

[英]C vs C++ initialization of static locals

I have the following code in both C and C++ 我在C和C ++中都有以下代码

static void callback(char const* fname, int status)
{
  static char const* szSection = fname;
  //other stuff
}

In C++ this compiles fine without warning or error. 在C ++中,这可以在没有警告或错误的情况下编译。 In CI get the compilation error "initializer is not constant". 在CI中获取编译错误“初始化程序不是常量”。 Why does it differ between the two? 为什么两者之间有所不同? I'm using the VC9 compiler for Visual Studio 2008 for both. 我正在为Visual Studio 2008使用VC9编译器。

I'm trying to take a filename as input and set the path to the file the first time. 我正在尝试将文件名作为输入,并在第一次设置文件的路径。 All further callbacks are used to check for updates in the file, but it is not permissible for the path itself to change. 所有进一步的回调都用于检查文件中的更新,但路径本身不允许更改。 Am I using the right variable in a char const*? 我在char const *中使用了正确的变量吗?

Because the rules are different in C and C++. 因为C和C ++中的规则不同。

In C++, static variables inside a function get initialized the first time that block of code gets reached, so they're allowed to be initialized with any valid expression. 在C ++中,函数内部的static变量在第一次到达代码块时被初始化,因此允许使用任何有效的表达式对它们进行初始化。

In C, static variables are initialized at program start, so they need to be a compile-time constant. 在C中, static变量在程序启动时初始化,因此它们需要是编译时常量。

Static variables in functions have to be initialized at compile time. 函数中的静态变量必须在编译时初始化。

This is probably what you want: 这可能是你想要的:

static void callback(char const* fname, int status)
{
  static char const* szSection = 0;
  szSection = fname;
  //other stuff
}

In C++, I would prefer to do something along these lines: 在C ++中,我更愿意沿着这些方向做点什么:

static void callback(char const* fname, int status)
{
  static std::string section;
  if( section.empty() && fname && strlen(fname) )
  {
    section = fname;
  }
  // other stuff
}

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

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