变量始终为空

kn0*_*ulo 1 c++ global initialization temporary lifetime

我在初始化全局变量时遇到了麻烦。我的 C++ 有点生疏,所以我不记得我的代码不起作用的原因。

文件.cpp

const char * write_path = &(std::string(getenv("FIFO_PATH")) + "/pythonread_fifo")[0];

int main(int argc, char**argv)
{
    std::cout << "printing a string: ";
    std::cout << (std::string(getenv("FIFO_PATH")) + "/pythonread_fifo\n");

    std::cout << "printing a const char*: ";
    std::cout << &(std::string(getenv("FIFO_PATH")) + "/pythonread_fifo")[0] << std::endl;

    std::cout << "printing write_path:";
    std::cout << write_path;
    std::cout << write_path << std::endl;

    std::cout << "printing FIFO_PATH:" << std::string(getenv("FIFO_PATH"));
}
Run Code Online (Sandbox Code Playgroud)

作为前提:FIFO_PATH 已正确添加到 bashrc,并且它可以工作,但是,当我启动此程序时,这是输出:

printing a string: /home/Processes/FIFOs/pythonread_fifo
printing a const char*: /home/Processes/FIFOs/pythonread_fifo
printing write_path:
printing FIFO_PATH:/home/Processes/FIFOs
Run Code Online (Sandbox Code Playgroud)

如您所见write_path,完全是空的。

对我来说更奇怪的是,如果我将 write_path 定义为:

 const char * write_path = "/home/Processes/FIFOs/pythonread_fifo";
Run Code Online (Sandbox Code Playgroud)

然后write_path不再为空,它已正确初始化和打印。

我该如何解决这个问题?或者至少,为什么会发生这种情况?

编辑:这个问题与write_path全球化无关。我将定义放在 main 中,当我尝试打印时write_path,它仍然是空的

son*_*yao 6

write_path被初始化为指向临时 1st 元素的指针std::string,它将在完整表达式后立即销毁,左write_path悬垂,对其取消引用导致 UB。

您可以std::string直接使用,也可以使用named std::string,然后从中获取指针。

std::string s = std::string(getenv("FIFO_PATH")) + "/pythonread_fifo";
const char * write_path = &s[0]; // or s.c_str()
Run Code Online (Sandbox Code Playgroud)

另一方面,

const char * write_path = "/home/mverrocc/dss_cp/dss-cp/Processes/FIFOs/pythonread_fifo";
Run Code Online (Sandbox Code Playgroud)

工作正常,c 样式字符串文字具有静态存储持续时间并在程序的生命周期中存在于内存中,然后write_path始终是一个有效的指针。