调用构造函数与将内联常量定义为默认参数

She*_*hep 1 c++ c++17

我有一个将配置结构作为参数的函数

struct Config
{
  Config(); //<-- default constructor
  // some configuration constants
};

int computeSomethingFrom(Something arg, const Config& config = Config());

Run Code Online (Sandbox Code Playgroud)

对于定义Config()computeSomethingFrom(...)都是相同的源文件英寸

我的猜测是,Config由于无法知道默认构造函数是否依赖于环境中的其他内容,因此将强制构造每个函数调用。如果配置结构变大或函数被多次调用,这可能会变得很昂贵。

不过,如果可以的话,我宁愿避免创建另一个常量。而且它的可能,因为默认的构造和功能相同的源文件中定义,编译器可以推断,Config()总是返回同样的事情。

那么有什么办法可以避免做类似的事情

inline Config DEFAULT_CONFIG = Config();
Run Code Online (Sandbox Code Playgroud)

然后将函数声明为

int computeSomethingFrom(Something arg, const Config& config = DEFAULT_CONFIG);
Run Code Online (Sandbox Code Playgroud)

Mar*_*k R 6

只是重载此功能:

int computeSomethingFrom(Something arg, const Config& config); // note no default value
int computeSomethingFrom(Something arg);
Run Code Online (Sandbox Code Playgroud)

我不知道这会如何影响您的代码,因为您没有提供任何信息computeSomethingFrom

可能的实现之一(可能您对此不会满意):

int computeSomethingFrom(Something arg)
{
    static const Config cfg;
    return computeSomethingFrom(arg, cfg);
}
Run Code Online (Sandbox Code Playgroud)