0

I have the following code:

void Foo() {

   static std::vector<int>(3);

   // Vector object is constructed every function call

   // The destructor of the static vector is invoked at
   // this point (the debugger shows so)
   // <-------------------

   int a;
}

Then somewhere I call Foo several times in a sequence

Why does the vector object gets constructed on every Foo() call and why is the destructor called right after static ... declaration?


Update:

I was trying to implement function once calling mechanism and I thought that writing something like

static core::CallOnce(parameters) where CallOnce is a class name would be very nice.

To my mind writing static core::CallOnce call_once(parameters) looks worse, but okay, this is the case I can't do anything with it.

Thank you.

Yippie-Ki-Yay
  • 22,026
  • 26
  • 90
  • 148

3 Answers3

12

Your variable needs a name:

static std::vector<int> my_static_vector(3);
James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • @Michael: Good question. Must find whoever keeps downvoting without leaving a freaking COMMENT! That is what they are for! (Oh, and +1) – Billy ONeal Aug 01 '10 at 04:03
  • @James Do you know by the chance, why does this happen? Why can't an unnamed object, which does some work in the constructor be a "normal" static variable and don't get constructed-destructed? – Yippie-Ki-Yay Aug 01 '10 at 04:07
  • 3
    @HardCoder1986: A variable must have a name. The code in your original question is not valid C++ (though at least one compiler accepts it without issuing a warning). Unnamed objects are temporaries and follow special lifetime rules (basically, they exist only until the end of the full expression in which they were created). – James McNellis Aug 01 '10 at 04:17
  • @Michael: If it was downvoted, the downvote was undone. Maybe it was just a mistake. – James McNellis Aug 01 '10 at 04:19
  • On a related note, that compiler vendor does not intend to fix that bug at this time. See https://connect.microsoft.com/VisualStudio/feedback/details/582129. – James McNellis Aug 12 '10 at 18:58
7

You forgot to give the vector a name, so without any variable pointing to it it's destroyed immediately after it's created

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
4

Because std::vector<int>(3) creates an unnamed temporary, which lives only to the end of it's contained expression. The debugger can't show destruction in the same line as construction though, so it shows it on the next line.

Give the item an name and normal static semantics will apply.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552