English 中文(简体)
是否取得了结果?
原标题:Does getenv cache the result?

我在守则中多次呼吁<代码>getenv<>/code>(所谓的许多时间),因此,我看到优化的潜力。 我的问题是,<代码>getenv,有些how在内部取得结果,或每打一个电话询问环境变数?

我对守则作了简介,getenv<>/code>不是瓶颈,但我仍然希望加以改动,这样会提高效率。

作为一个次要问题,在方案运行期间,能否改变环境变量? 我不这样做,因此,如果我错失结果,那将是安全的,那是公正的。

问题回答

环境变量通常生活在特定过程的记忆中,因此,那里没有任何东西可以藏匿,而且很容易获得。

关于最新信息,如果你预计会发生的话,运行过程的任何组成部分都可以称作putenv<>code>,以更新环境。

我怀疑,它预示着成果,环境变量可能从呼吁转变为呼吁。 您可以执行这一方针:

#include <map>
#include <iostream>
#include <string>
#include <stdexcept>
#include <cstdlib>


class EnvCache {
public:
    const std::string &get_env(const std::string &key) {
        auto it = cache_entries.find(key);
        if(it == cache_entries.end()) {
            const char *ptr = getenv(key.c_str());
            if(!ptr)
                throw std::runtime_error("Env var not found");
            it = cache_entries.insert({key, ptr}).first;
        }
        return it->second;
    }

    void clear() {
        cache_entries.clear();
    }
private:
    std::map<std::string, std::string> cache_entries;
};

int main() {
    EnvCache cache;
    std::cout << cache.get_env("PATH") << std::endl;
}

如果你改变环境变量,你就可以使切入无效。 你还可以直接绘制<代码>const char*,但这要看你。





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?