从技术上讲,您的代码很好。
但是您所编写的方式很容易使不知道该代码的人破解。对于c_str(),唯一安全的用法是将其作为参数传递给函数时。否则,您将面临维护问题。
范例1:
{
std::string server = "my_server";
std::string name = "my_name";
Foo foo;
foo.server = server.c_str();
foo.name = name.c_str();
//
// Imagine this is a long function
// Now a maintainer can easily come along and see name and server
// and would never expect that these values need to be maintained as
// const values so why not re-use them
name += "Martin";
// Oops now its broken.
// We use foo
use_foo(foo);
// Foo is about to be destroyed, before name and server
}
因此,为了维护,请使其明显:
更好的解决方案:
{
// Now they can't be changed.
std::string const server = "my_server";
std::string const name = "my_name";
Foo foo;
foo.server = server.c_str();
foo.name = name.c_str();
use_foo(foo);
}
但是,如果您有const字符串,则实际上并不需要它们:
{
char const* server = "my_server";
char const* name = "my_name";
Foo foo;
foo.server = server;
foo.name = name;
use_foo(foo);
}
好。由于某些原因,您希望它们作为字符串:
为什么不只在调用中使用它们:
{
std::string server = "my_server";
std::string name = "my_name";
// guaranteed not to be modified now!!!
use_foo(Foo(server.c_str(), name.c_str());
}
.c_str()
。我不明白为什么有时有时只得到字符串的一部分,直到我知道字符串const char*
不会永远存在,而是直到字符串被销毁为止