从技术上讲,您的代码很好。
但是您编写的方式很容易让不知道代码的人破解。对于 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());
}