Is it better to use `static const std :: string` or just` const std :: string` in a method / function?

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 just an example)

  • static const It will be initialized only once, but it is stored in memory until the process is completed.
  • constwill be initialized every time it is executed foo(), but the memory (stack) is freed when the block is completed {}.

On the other hand, the string "SELECT ... "must still be hard-coded in the program code. And that doesn’t matter if we use 1. or 2.

So which approach is better? Using static const std::stringor just const std::string?

, , , , foo() - 1000 ( ) 1000 ( ).

( static const char * const char * qaru.site/questions/364264/..., const char*.)

+4
4

. , , .

, . GCC, ++ 11 , , Microsoft , VS2013 , Microsoft.

+2

, -, static const , const . :

, , . , .

, gcc , MS ++ , , .

, -, . , . , , , . , .

+1

, "" . 1) const, , :

const int var = 9;
int b = sqrt( var );

int b = sqrt( 9 );

, #define C. , , "".

2) , foo(). , .

0

- (const ) ( ). ( GCC) , . strSQL, , (- ), , .

:

void call(std::string const& where) {
    static char prefix[] = "SELECT ...";

    std::string strSQL;
    strSQL.reserve(sizeof(prefix)/sizeof(char) + strWHERE.size()); 
    strSQL.append(prefix, sizeof(prefix)/sizeof(char)).append(strWHERE);
    ...
}

, .

0

Source: https://habr.com/ru/post/1523497/


All Articles