dav*_*dav 0 c++ variables environment const getenv
对于使用大量环境变量的应用程序,在获取环境变量并将它们放入结构或一堆结构中时,是否存在某种约定或"最佳实践" const?显然,我想回退到每个环境变量的默认值.现在,使用以下内容似乎是一种非常混乱的方式:
char* x;
const SOME_VARIABLE;
if (NULL == (x = getenv("SOME_VARIABLE")))
SOME_VARIABLE = 5; // default value
else
SOME_VARIABLE = x;
Run Code Online (Sandbox Code Playgroud)
getenv如果环境变量为空,我还可以编写一个包装函数来返回默认值,但我不确定这是否是最好的方法.我也可以放弃使用const,但这似乎也不是一件好事.
有什么想法吗?
怎么样:
std::string GetEnvironmentVariableOrDefault(const std::string& variable_name,
const std::string& default_value)
{
const char* value = getenv(variable_name.c_str());
return value ? value : default_value;
}
Run Code Online (Sandbox Code Playgroud)
用作:
const std::string some_variable = GetEnvironmentVariableOrDefault("SOME_VARIABLE", "5");
Run Code Online (Sandbox Code Playgroud)