What is the lifetime of the result of std::string::c_str()?(std::string::c_str() 结果的生命周期是多少?)
问题描述
在我的一个程序中,我必须与一些使用 const char* 的遗留代码交互.
In one of my programs, I have to interface with some legacy code that works with const char*.
假设我有一个如下所示的结构:
Lets say I have a structure which looks like:
struct Foo
{
const char* server;
const char* name;
};
我的上层应用只处理std::string,所以想到了用std::string::c_str()来取回const char* 指针.
My higher-level application only deals with std::string, so I thought of using std::string::c_str() to get back const char* pointers.
但是 c_str() 的生命周期是多少?
But what is the lifetime of c_str() ?
我可以在不面对未定义行为的情况下做这样的事情吗?
Can I do something like this without facing undefined behavior ?
{
std::string server = "my_server";
std::string name = "my_name";
Foo foo;
foo.server = server.c_str();
foo.name = name.c_str();
// We use foo
use_foo(foo);
// Foo is about to be destroyed, before name and server
}
还是我应该立即将 c_str() 的结果复制到另一个地方?
Or am I supposed to immediately copy the result of c_str() to another place ?
谢谢.
推荐答案
如果 std::string 被销毁或非-const 字符串的成员函数被调用.因此,如果您需要保留它,通常您会想要制作它的副本.
The c_str() result becomes invalid if the std::string is destroyed or if a non-const member function of the string is called. So, usually you will want to make a copy of it if you need to keep it around.
在您的示例中,c_str() 的结果似乎是安全使用的,因为在该范围内不会修改字符串.(但是,我们不知道 use_foo() 或 ~Foo() 可能对这些值做什么;如果他们将字符串复制到别处,那么他们应该做一个真正的复制,而不仅仅是复制char指针.)
In the case of your example, it appears that the results of c_str() are used safely, because the strings are not modified while in that scope. (However, we don't know what use_foo() or ~Foo() might be doing with those values; if they copy the strings elsewhere, then they should do a true copy, and not just copy the char pointers.)
这篇关于std::string::c_str() 结果的生命周期是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::string::c_str() 结果的生命周期是多少?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
