我有一个方法/函数:
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只是一个例子)
static const
只会初始化一次,但持续存在于内存中直到进程结束。const
每次运行foo()
时都会初始化,但是内存(堆栈)在{}
块结束时释放。
另一方面,字符串"SELECT ... "
仍必须硬编码在程序代码中。使用1或2并不重要。
那么哪种方法更好?是使用static const std::string
还是只用const std::string
?
或者可能没有一个答案,因为它取决于我如何使用foo()
——每秒调用它1000次(那么我不想每次都初始化变量)还是每月调用它1000次(那我不关心)。
(我已经阅读了问题Difference between static const char* and const char*,特别是回答https://dev59.com/03A85IYBdhLWcg3wHv3B#2931146,但它们适用于const char*
。)
const char* const strSQLQuery = "SELECT ... "
。 - Jarod42