开发者

C++ static members

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.


Your variable needs a name:

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜