I have a method / function:
void foo() {
static const std::string strSQLQuery = "SELECT ... ";
// or maybe
const std::string strSQLQuery = "SELECT ... ";
// some operations on strSQLQuery
// i.e. concatenating with WHERE, etc.:
const std::string strSQL = strSQLQuery + strWHERE;
doSthOnDataBase(strSQL);
}
(SQL is only an example)
static const
will be initialized only once, but persists in memory until the process ends.const
will be initialized every timefoo()
is run, but the memory (stack) is freed when the{}
block ends.
On the other hand, the string "SELECT ... "
has to be still hardcoded in the program code. And it's no matter if we use 1. or 2.
So which approach is better? Using static const std::string
or only const std::string
?
Or maybe there's no one answere, because it depends how I want to use foo()
-- call it 1000 times per second (then I don't want to initialize a variable every time) or call it 1000 times per month (then I don't care).
(I've read Question Difference between static const char* and const char* and especially answer https://stackoverflow.com/a/2931146/945183, but they apply to const char*
.)