Search code examples
c++scopeinitializer-list

Scope of a variable initialized in the parameter list of a function


The following code builds, compiles and runs (C++, mingw) seemingly without any problems. However, am I guaranteed that objects constructed with initializer-lists inside a function's parameter list, lives through the scope of that function, even though the function takes the argument by reference?

If not, is it true that when creating an object using its initializer-list in a function's parameter list (which takes the argument by reference) may be dangerous because it will immediately be destructed: In this case, the function doesn't have a copy, but a reference to memory which may, or may not be reallocated by another process?

struct S
{
  S() : a(0), b(0) {}
  S(int a, int b) : a(a), b(b) {}
  int a;
  int b;
};

void foo(const S& s)
{
  std::cout << "s.a = " << s.a << std::endl;
  std::cout << "s.b = " << s.b << std::endl;
}

int main()
{
  foo({4,5}); // <-- What is the scope of the struct initialized here?

  return 0;
}

Solution

  • According to cppreference [lifetime]:

    All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created, and if multiple temporary objects were created, they are destroyed in the order opposite to the order of creation. This is true even if that evaluation ends in throwing an exception.

    That means that the temporary object will be destroyed after the function has returned, so it's perfectly safe.