技術的には、あなたのコードは問題ありません。
しかし、コードを知らない人が簡単に壊れるような方法で書いています。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());
}