const char* convert 有问题导致打印无

const char* convert have problem result in print nothing

提问人:cat 提问时间:6/29/2023 更新时间:6/29/2023 访问量:20

问:

我尝试将uint64_t转换为 const char *。但是我发现如果我使用
,它什么也打印不出来。
const char *sz2 = std::to_string(channel_id2).c_str();

当我使用字符串获取 std::to_string(channel_id2) 的结果并将字符串转换为 const char * 时,它可以正常打印信息。然后我做其他实验。

enter image description here

enter image description here

enter image description here

字符串 指针 const-char

评论


答:

0赞 robthebloke 6/29/2023 #1

这很好:

// This creates a temp string
std::string temp = std::to_string(channel_id2);

// This is fine, because temp is a variable (and so exists in memory)
const char *sz2 = temp.c_str();

但是,当您这样做时:

const char *sz2 = std::to_string(channel_id2).c_str();

操作顺序为:

  1. 调用,这将生成一个临时字符串对象。std::to_string
  2. 用于获取指向临时字符串内容的指针c_str()
  3. 释放临时字符串(从而释放 sz2 也指向的内存)

结果是 sz2 指向任何有效的东西,因此你得到的是无意义的结果

或者将一行代码翻译成多行代码,这就是正在发生的事情:

const char *sz2; //< uninitialised

// scope the lifespan of the temporary
{
  // generate temp
  std::string temp = std::to_string(channel_id2);

  // grab address..
  sz2 = temp.c_str();

  // at this point, the destructor of temp is called... 
}

// now sz2 is invalid from here