I'm starting with this code:
void func1() {
char tmpfile[] = "/tmp/tmpXXXXXX";
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = "/tmp/tmpXXXXXX";
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
I'd like to refactor this to pull out the shared "/tmp/tmpXXXXXX" constant. Here is an attempt:
constexpr char kTmpfile[] = "/tmp/tmpXXXXXX";
void func1() {
char tmpfile[] = kTmpfile;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = kTmpfile;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
However, this doesn't compile. Changing tmpfile[] to tmpfile[sizeof(kTmpfile)] also doesn't work.
The below does work, but it uses a macro which is discouraged by my company's style guide (which is based on the Google Style Guide).
#define TMPFILE "/tmp/tmpXXXXXX"
void func1() {
char tmpfile[] = TMPFILE;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
void func2() {
char tmpfile[] = TMPFILE;
mkstemp(tmpfile); // Note: mkstemp modifies the char array, cannot be const
...
}
Is there any way to write this "nicely"? Without having to use a macro or hardcode the size? Or is the macro the best option for readability and maintainability?
std::string?tmpfilearrays are function-local, you should be able to replacechar tmpfile[] = STR_LITERAL;withchar tmpfile[sizeof kTmpfile]; memcpy(tmpfile,kTmpfile,sizeof kTmpfile);with no loss of efficiency.mkstempthat makes things more c++-esque. Something likestd::string my_mkstemp(std::string)and then you can do all the ugliness ofstrcpy'ing into a char array and stuff in one place and reuse it everywhere.std:stringmaybe along withstd::string::data()/std::string::c_str().