相关疑难解决方法(0)

什么是std :: string :: c_str()生命周期?

在我的一个程序中,我必须与一些可用的遗留代码进行交互const char*.

可以说我的结构看起来像:

struct Foo
{
  const char* server;
  const char* name;
};
Run Code Online (Sandbox Code Playgroud)

我的高级应用程序只处理std::string,所以我想用std::string::c_str()回来const char*指针.

但是它的寿命是c_str()多少?

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

{
  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
}
Run Code Online (Sandbox Code Playgroud)

或者我应该立即将结果复制c_str()到另一个地方?

谢谢.

c++ string cstring

92
推荐指数
3
解决办法
3万
查看次数

标签 统计

c++ ×1

cstring ×1

string ×1