Technically, your code is fine.
BUT , you wrote in such a way that it was easy to break for someone who does not know the code. For c_str (), the only safe use is when you pass it as a parameter to a function. Otherwise, you will discover maintenance problems.
Example 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 }
So, for maintenance, make this obvious:
The best decision:
{
But if you have constant strings, you really don't need them:
{ char const* server = "my_server"; char const* name = "my_name"; Foo foo; foo.server = server; foo.name = name; use_foo(foo); }
OK For some reason you want them to be like strings:
Why not use them only in a call:
{ std::string server = "my_server"; std::string name = "my_name";
Loki Astari Jun 23 2018-11-11T00: 00Z
source share