I wrote a program a while ago in c language and want to move to c++, I had:
BuiltInCommand(const char* cmd_line);
what is the best way to use string here?
BuiltInCommand(const string cmd_line);
or
BuiltInCommand(const string& cmd_line);
I wrote a program a while ago in c language and want to move to c++, I had:
BuiltInCommand(const char* cmd_line);
what is the best way to use string here?
BuiltInCommand(const string cmd_line);
or
BuiltInCommand(const string& cmd_line);
Since you have that cmd_line
characters are not modifiable from the function, I would suggest to use:
BuiltInCommand(const string& cmd_line);
In this way you don't copy the entire string but you pass it by reference (similarly to what you are doing with char*). (In c++ you can use passage by reference, by value or using pointers. For more information check passage by reference)
However, there is also the option of using char*
in c++... But I guess you already knew so.
what is the best way to use string here?
It depends on what the function does.
If you intend to store a copy of the string, then BuiltInCommand(std::string)
would be a good default choice.
If you don't intend to store a copy, then best choice is typically to not use std::string
here. Often a better choice is to use BuiltInCommand(std::string_view)
.
std::string_view
however doesn't require the string to be null terminated. In many cases that isn't a problem, but if the function has to internally use some C API that relies on null termination and that cannot be changed, then it is fine to keep using const char*
in C++.