0

Suppose I have a template

template <unsigned int SIZE=512>
structure Sql
{ 
      const char * operator()(const char* format, ...)
        {
               deal format string here ...
                return sql;
         }
private:
         char sql[SIZE];
}

I have another function:

int dbSelect (const char* sql, void *outdata)
{
    use sql to query database here...
}

void main()
{
    dbSelect(Sql<>()(“select data from abc where column =%u”,32u),&outdata);
}

Use Sql like this is safe? Sql<>() will create a temporary object ,what is the temporary object’ life time? During the dbSelect body,the temporary object’s sql[512] is still available to access? Is still valid to access?

vsoftco
  • 53,843
  • 10
  • 127
  • 237
  • `Sql<>()` creates an automatic variable, so it will be destroyed when the closing brace of the enclosing function is reached. – Edward Karak Jan 03 '18 at 03:00
  • 1
    Nope, it's a temporary variable, and lifetimes of temporaries are much shorter. – Sam Varshavchik Jan 03 '18 at 03:53
  • 1
    @SamVarshavchik how come? I run those code on visual studio 2015 and Linux ,both get same results ,could it be the results totally depend on the compiler? – zhangxiaoguo Jan 03 '18 at 05:03

1 Answers1

3

Yes it is safe, the lifetime of the temporary Sql<>() object is prolonged until the end of the full expression (the semicolon in your case):

dbSelect(Sql<>()(“select data from abc where column =%u”,32u),&outdata);
                                                                        ^^^^ 
                                                      here Sql<>() ceases to be valid

Related: C++: Life span of temporary arguments?

vsoftco
  • 53,843
  • 10
  • 127
  • 237