多个std :: String临时,导致相同的C_STR指针
Multiple std::string temporaries resulting in the same c_str pointer
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
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 为什么使用 "this" 指针调用派生成员函数?
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用指针从C++中的数组中获取最大值
- 助记符和指向成员语法的指针
- 嵌入方指针压缩已禁用
- 数组的指针从不分段故障
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 何时在引用或唯一指针上使用移动语义
- QMetaObject invokeMethod的基于函数指针的语法
- 如何从 std::atomic 中提取指针 T<T>?
- 如何在 C# 中映射双 C 结构指针?
- C++将浮点指针值舍入为小数位数
- 为什么++(*p)更改指针值
- 为什么在使用字符指针 str1 而不是 str 时会出现分段转储?
- 超级级别的方法称为super具有sub的str attr 实例在循环 实例中创建的方法是作为super的指针存储在向
- 为什么当我们反转此函数中的字符串时,char *str 的指针没有改变?
- basic_ostringstream::str悬挂指针
- 删除指针后,str 指针自身的占用空间可以存在