简体   繁体   中英

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;
}

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.

Here prvalue materialized to create temporary object of type S from the braced-init-list {4,5} , which is destroyed at the end of the full-expression. In your case foo({4,5}); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM