简体   繁体   English

使用静态成员函数初始化初始化列表中的常量成员变量是否有任何问题?

[英]Are there any problems in using a Static Member Function to initialize a Constant Member Variable in an Initializer List?

I wish to have a class in my program that directly takes the Command Line arguments from the main method. 我希望在我的程序中有一个类直接从main方法获取命令行参数。 I want some of this information to be Constant to the Class, but also dependant upon the Command Line arguments that were entered. 我希望这些信息中的一些信息是Class的Constant,但也取决于输入的命令行参数。

I have read the detailed answer here: C++ defining a constant member variable inside class constructor , however I am still a little confused... 我在这里已经阅读了详细的答案: C ++在类构造函数中定义一个常量成员变量 ,但是我仍然有点困惑......

main.cpp: main.cpp中:

#include "Launcher.h"

int main(int argc, char *argv[]) {
    Launcher launcher(argc, argv);

    // do other stuff with launcher

    return 0;
}

Launcher.h: Launcher.h:

#ifndef LAUNCHER_H
#define LAUNCHER_H

#include <string>
#include <vector>

class Launcher {
public:
    Launcher(int, char *[]);

private:
    const int argumentCount;
    const std::vector<std::string> arguments;

    static const std::vector<std::string> INIT_arguments(int, char *[]);
};

#endif

Launcher.cpp Launcher.cpp

#include "Launcher.h"

Launcher::Launcher(int inputCount, char *inputArguments[]) :
    argumentCount(inputCount),
    arguments(INIT_arguments(inputCount, inputArguments))
{}

Launcher::INIT_arguments(int inputCount, char *inputArguments[]) {
    std::vector<std::string> argumentVector;
    for (int i = 0; i < inputCount; i++) {
        std::string currentArgument = inputArguments[i];
        argumentVector.push_back(currentArgument);
    }
    return argumentVector;
}

(I understand that in this example there may be alternative methods to achieve the same results by not using an initializer lists. In other cases I've used complex functions to determine the const variable's value but chose this simple example to demonstrate the concept.) (我知道在这个例子中可能有替代方法通过不使用初始化列表来实现相同的结果。在其他情况下,我使用复杂的函数来确定const变量的值,但选择了这个简单的例子来演示这个概念。)

My questions are: 我的问题是:

  1. Are there any problems with initializing a const member variable by using a static function(In the example above)? 使用静态函数初始化const成员变量是否有任何问题(在上面的例子中)?
  2. Does anything change / are there any more problems if the function used to initialize the const variable is non-static? 如果用于初始化const变量的函数是非静态的,那么有什么改变/是否还有问题?
  3. Is there any difference between defining the function in the header file alongside its declaration versus how its been declared in the header file then defined in the source file? 在头文件中定义函数及其声明与在源文件中定义的头文件中声明函数之间有什么区别吗? Are there any differences if it's static/non-static? 如果它是静态/非静态的,有什么区别吗?
  4. Unrelated to the general question but... Is there an easy way to pass the char *[] variable by reference or perhaps a more efficient way? 与一般问题无关但是......有没有一种简单的方法可以通过引用或者更有效的方式传递char * []变量?

Are there any problems with initializing a const member variable by using a static function(In the example above)? 使用静态函数初始化const成员变量是否有任何问题(在上面的例子中)?

No. One could argue that such a local helper function that has little to do with your actual class could instead be outsourced into a helper/utility entity, maybe a free function (template) in an anonymous namespace or somewhere else (to make it testable). 没有人可能会争辩说,与你的实际类没什么关系的这样一个本地帮助函数可以改为外包到一个帮助器/实用程序实体,可能是一个匿名命名空间或其他地方的自由函数(模板)(使其可测试) )。

Does anything change / are there any more problems if the function used to initialize the const variable is non-static? 如果用于初始化const变量的函数是非静态的,那么有什么改变/是否还有问题?

Making it static ensures that the member function has nothing to do with any of the instances' state (same for free functions, obviously). 使其成为static可确保成员函数与任何实例的状态无关(显然,对于自由函数也是如此)。 I would definitely keep it that way for functions that are used to initialize state. 对于用于初始化状态的函数,我肯定会保持这种方式。

Is there any difference between defining the function in the header file alongside its declaration versus how its been declared in the header file then defined in the source file? 在头文件中定义函数及其声明与在源文件中定义的头文件中声明函数之间有什么区别吗?

No. If you would make it a free function though, you need to take care of possible ODR violations, and at least mark it as inline . 不会。但是,如果您将其设为免费功能,则需要处理可能的ODR违规,并至少将其标记为inline

Is there an easy way to pass the char *[] variable by reference or perhaps a more efficient way? 有没有一种简单的方法可以通过引用或者更有效的方式传递char * []变量?

There is a more efficient way, ie, not using the function at all and rely on the std::vector constructor (overload #4) that takes two iterators as arguments. 有一种更有效的方法,即根本不使用该函数,并依赖于将两个迭代器作为参数的std::vector构造函数 (重载#4)。 Pointers to the same raw array are fine here, so you can just do: 指向相同原始数组的指针在这里很好,所以你可以这样做:

Launcher::Launcher(int inputCount, char *inputArguments[]) :
   argumentCount(inputCount),
   arguments(inputArguments, inputArguments + inputCount) {}

Note also that Launcher doesn't seem to intend modifying the command line arguments. 另请注意, Launcher似乎不打算修改命令行参数。 In this case, you don't have to copy the strings at all. 在这种情况下,您根本不必复制字符串。 Use a std::string_view instead (if C++17 is available) or just leave it as const char* (one nice thing about command line arguments is that you don't have to think about their lifetime). 使用std::string_view (如果C ++ 17可用)或者将其保留为const char* (关于命令行参数的一个std::string_view是你不必考虑它们的生命周期)。

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

相关问题 如何使用函数初始化静态常量成员 - How to initialize static constant member using function 如何在运行时使用静态成员函数初始化静态成员变量? - How to initialize a static member variable using a static member function at runtime? 在嵌套类中初始化静态常量成员变量 - Initialize static constant member variable in nested class 在初始化列表中使用复杂函数来初始化const成员一个好的设计? - Is using a complex function in initializer list to initialize const member a good design? 使用在初始化列表中早先初始化的成员初始化成员是否安全? - Is it safe to initialize a member using a member initialized earlier in initializer list? 静态成员函数初始化静态成员变量 - 用法和风险? - Static member function to initialize static member variable - usage and risks? 成员函数内的静态初始化程序需要编译时常量吗? - Static initializer inside member function require compile-time constant? 如何在初始化列表中初始化普通数组成员变量? - How can I initialize normal array member variable in initializer list? 成员初始化列表:从返回元组的函数初始化两个成员 - Member initializer list: initialize two members from a function returning a tuple 初始化任何联合成员(指定初始化器) - Initialize Any Union Member (designated initializer)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM