C++ 中 c_str() 和 char* 的不等式

Inequality of c_str() and char* in C++

我相信我刚刚找到了过去几天一直困扰我的错误,但它的含义让我很头疼。

我在 macOS mojave 机器上使用本地 libcurl 工具(在 /usr/lib 中),但我认为 cURL 本身不是问题所在。

我一直在尝试使用以下代码向 Twitter 提交 OAuth2 请求,所有 headers 均已正确提供(未显示)。

// supplying https://api.twitter.com/oauth2/token?grant_type=client_credentials for ease of use
curl_easy_setopt(curl, CURLOPT_URL, "https://api.twitter.com/oauth2/token");
std::string grantType = "grant_type=client_credentials";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, grantType.c_str());

但是,这失败了,状态码为

{"errors":[{"code":170,"message":"Missing required parameter: grant_type","label":"forbidden_missing_parameter"}]}

困惑,我试了一下:

curl_easy_setopt(curl, CURLOPT_URL, "https://api.twitter.com/oauth2/token");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "grant_type=client_credentials");

完美运行:

{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAIMu6QAAAAAArr86Rv2W70fTicd4yAir7..."}

所以要么我不了解 C++ 的一个关键方面,要么我已经打破了宇宙 — 为什么调用 c_str() 不会产生相同的输出?

我也在一个单独的项目中 运行 以下内容,以尝试了解正在发生的事情。

std::string string1 = "test";
char* string2 = "test";
assert((strcmp(string1.c_str(), string2)) || (string1.c_str() == string2));

为什么定义一个 char* 与定义一个字符串然后调用 c_str() 产生的值不同?

仅考虑您的第二个项目,代码中断言检查的第二部分:

std::string string1 = "test";
char* string2 = "test";
assert((strcmp(string1.c_str(), string2)) || (string1.c_str() == string2));

是比较string1.c_str()存放的地址和存放string2的地址,会不一样。

结果实际上是一个字符串生命周期问题,alter igel 指出:CURL_POSTFIELDS 必须在稍后的执行点访问字符串值,但此时字符串已经消失范围并已从内存中删除。创建变量作为方法的参数必须自动创建一个 char* 文字,它不会被编译器尽快销毁,从而导致我上面概述的行为。谢谢您的帮助!