C++ extern const char* 没有按预期工作

C++ extern const char* not working as expected

我以前使用过 extern 关键字,但现在我遇到了一个非常奇怪的问题。

首先我有包含外部变量声明的 common.hh 文件:

//some extern declarations
extern const char* PATH;

在我的 main.cc 中,我执行以下操作(暂时忽略 cout):

#include "common.hh"
const char* PATH;

int main(const int argc, const char* argv[]){
PATH = somePath.c_str();
//std::cout << PATH << std::endl; //will print the correct path
//std::cout << std::string(PATH) << std::endl; //will fix the problem occuring later
//some function calls to other files where PATH is used
//... somePath still in scope ...
//... somePath is about to be destroyed
}

现在我有其他文件 Other.hh 和 Other.cc 出现问题的地方: 首先是我的 Other.hh

#include "common.hh"
//function declarations and some other stuff

在Other.cc访问PATH时出现问题:

#include "Other.hh"
void someFunction(...){
std::cout << PATH << std::endl; //When accessing PATH here again it prints garbage

在我的文件 Other.cc 中,我需要在 main.cc 中定义的 const char* PATH,但由于某种原因 PATH 已更改。如果我在 main.cc 中的某处执行 std::string(PATH) ,整个问题就解决了,如上面的 cout 所示。我不明白哪里出了问题,我的所有其他外部变量都工作正常。

编辑: 问题暂时解决。我刚刚在 main.cc 中做了以下操作:

std::string tmp = somePath;
PATH = tmp.c_str();

我只是不明白为什么这样可以解决问题,因为理论上 tmpsomePath 应该具有相同的作用域,并且在 [=47= 中的函数调用之前不应被销毁] 被处决。换句话说:我在 other.cc 中的函数调用在 somePath 的范围结束之前。

somePath.c_str() 的生命周期受限于 somePath 变量。一旦超出范围,PATH 就会指向将被重新使用的内存。

你能把 PATH 变成 std::string 而不是 char* 吗?如果不是,您将不得不使用 strdup 或类似的东西复制 somePath.c_str() 的值。

c_strstd::string 的一种方法,它在字符串被更改或破坏时变得无效。例如,在之前的 question.

中查看有关 c_str 生命周期的详细信息

您可以制作 PATH 一个 std::string 并让它制作一个副本,或者您自己手动制作一个副本到分配了足够内存的 char * 中。然后考虑何时解除分配。


编辑 - 回复您的编辑

你在哪里

std::string tmp = somePath;
PATH = tmp.c_str();

你声称 "tmp and somePath should have the same scope" - 他们没有。 PATH 在全局范围内,您已在此处指定它指向 tmpc_str()