如何将std::stringa 转换为a char*或a const char*?
在我的一个程序中,我必须与一些可用的遗留代码进行交互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()到另一个地方?
谢谢.
我们有一个遗留方法,返回一个vectorchar指针,即vector<char *>.现在,我只需要处理字符串(std::string).我怎样才能做到这一点?
这个问题可能听起来很简单,但我遇到了几个网站,这些网站描述了这些考虑因素可能会导致内存泄漏.
现在,我要么得到一个vector<string>甚至是一个没有任何内存泄漏的字符串.我怎样才能做到这一点?