多个std :: String临时,导致相同的C_STR指针

Multiple std::string temporaries resulting in the same c_str pointer

本文关键字:STR 指针 String std 临时 多个      更新时间:2023-10-16

i具有返回 std::string的函数。我将其传递给printf,并创建一个用常见参数调用函数的辅助函数,并返回std::string中的C字符串指针。我会为每个呼叫获得相同的指针。我认为这与临时寿命有关。我想解决此问题并确保安全。

#include <stdio.h>
#include <string>
std::string intToString(int num) {
  char buf[100];
  snprintf(buf, sizeof(buf), "%d", num);
  return buf;
}
const char *helper(int num, int increment) {
  return intToString((num + increment) * 10).c_str();
}
int main() {
  for (int i=1; i < 5; i++) {
    printf("- %d: %3s  %3s  %3s  %3sn", i,
           intToString((i + 0) * 10).c_str(),
           intToString((i + 1) * 10).c_str(),
           intToString((i + 2) * 10).c_str(),
           intToString((i + 3) * 10).c_str()
           );
    printf("+ %d: %3s  %3s  %3s  %3sn", i,
           helper(i, 0),
           helper(i, 1),
           helper(i, 2),
           helper(i, 3)
           );
  }
  return 0;
}

输出:

- 1:  10   20   30   40
+ 1:  10   10   10   10
- 2:  20   30   40   50
+ 2:  20   20   20   20
- 3:  30   40   50   60
+ 3:  30   30   30   30
- 4:  40   50   60   70
+ 4:  40   40   40   40

只要字符串对象存在并且未修改,c_str()的返回值才有效。像您在helper中一样从临时返回它是不正确的。改用std::string,仅在您实际需要将其用作C弦的网站上使用c_str()

参考:http://www.cplusplus.com/reference/string/string/c_str/

这是仅使用C 对象和流的等效代码:

#include <iostream>
#include <string>
#include <iomanip>
std::string helper(int num, int increment) {
  return std::to_string((num + increment) * 10);
}
int main() {
  for (int i=1; i < 5; i++) {
      std::cout << "- " << i 
      << ": " << std::setw(3) << std::to_string((i + 0) * 10)
      << "  " << std::setw(3) << std::to_string((i + 1) * 10)
      << "  " << std::setw(3) << std::to_string((i + 2) * 10)
      << "  " << std::setw(3) << std::to_string((i + 3) * 10)
      << 'n'; 
      std::cout << "+ " << i 
      << ": " << std::setw(3) << helper(i, 0)
      << "  " << std::setw(3) << helper(i, 1)
      << "  " << std::setw(3) << helper(i, 2)
      << "  " << std::setw(3) << helper(i, 3)
      << 'n'; 
  }
  return 0;
}

预期输出:

- 1:  10   20   30   40
+ 1:  10   20   30   40
- 2:  20   30   40   50
+ 2:  20   30   40   50
- 3:  30   40   50   60
+ 3:  30   40   50   60
- 4:  40   50   60   70
+ 4:  40   50   60   70