简体   繁体   English

在C ++中,如何在类中初始化不可复制的静态成员变量?

[英]In C++, how to initialize an non-copyable static member variable in class?

I'm mimicking the code here: http://www.boost.org/doc/libs/1_59_0/doc/html/program_options/tutorial.html#idp343130416 . 我在这里模仿代码: http : //www.boost.org/doc/libs/1_59_0/doc/html/program_options/tutorial.html#idp343130416 I want to rewrite the code in a class, using static members to implement the functionality. 我想使用静态成员实现功能来重写类中的代码。

However, I found I can't initialize non-copyable static member variable in class. 但是,我发现无法在类中初始化不可复制的静态成员变量。 For example, in the class, the following code doesn't work: 例如,在该类中,以下代码不起作用:

class ProgramOptions{
private:
static po::options_description config("Generic options");
}
// Possible reason: visual studio treat it as function declaration.

class ProgramOptions{
private:
static po::options_description config = po::options_description config("Generic options");
}
// Possible reason: in C++, only the int type can be done this way. 
// For other types, static variable can't be evaluated where it's declared.

class ProgramOptions{
private:
static po::options_description config;
static void InitializeSaticMemberVariables()
    {
        generic = po::options_description("Generic options");
    }
}
// warning C4512: assignment operator cannot be generated.
// Possible reason: options_description is not copyable and the operator = has been intentionally disabled.

I searched many pages still failed to solve it. 我搜索了许多页面仍无法解决它。 What should I do? 我该怎么办?

I don't want to manage the members in the non-static way, since it's weird to have many instances of program options. 我不想以非静态方式管理成员,因为有很多程序选项实例很奇怪。

The first alternative should work if your compiler supports C++11 and brace-initialization: 如果您的编译器支持C ++ 11和brace-initialization,则第一个替代方法应该起作用:

static po::options_description config{"Generic options"};

Note that you still need to actually define the variable as well. 请注意,您仍然还需要实际定义变量。


The second variant could possibly be used, but you initialize the variable in the definition : 可以使用第二种变体,但是您可以在定义中初始化变量:

class ProgramOptions{
private:
    static po::options_description config;
    ...
};

...

po::options_description ProgramOptions::config = po::options_description config("Generic options");

However, this breaks the non-copyable point, as it will use the copy-constructor. 但是,这将破坏不可复制的点,因为它将使用复制构造函数。

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

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