什么是std :: string :: c_str()生存期? [英] What is std::string::c_str() lifetime?

查看:132
本文介绍了什么是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()的生命周期是什么?

我可以这样做,而不面对未定义的行为吗?

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 ?

谢谢。

推荐答案

c_str() 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()生存期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆