Reputation: 645
I am using a static vector inside a member function and pushing back values into that vector; but the size of vector is only 1 for three function calls.
I am not sure how to make MVCE for this as in MVCE it is working fine for me too, so the problem is obviously some other part of code. I just want to know or have an idea under which circumstances would my static vector give me such results.
class X
{
//...
};
template <typename T>
void test(T a)
{
std::cout<<"Function called \n";
static std::vector<X> vec;
std::lock_guard<std::mutex> lock(mx);
//Doing something else with T
X obj;
vec.push_back(obj);
std::cout<<"no of elements in vec is "<<vec.size()<<"\n";
}
The output coming is
Function called
no of elements in vec is 1
Function called
no of elements in vec is 1
Function called
no of elements in vec is 1
The member function is called from the CPPREST http_client request call.
Upvotes: 4
Views: 1205
Reputation: 105
Your request call probably looks similar to this int i = 1; float f = 2.5; char c = 'A'; test(i); test(f); test(c);
If you add test(i);
Then vec.size() for test(int) will be 2 While vec.size() for test(float) and test(char) will stay 1.
You can read more about the behavior of static variables in templates here http://www.geeksforgeeks.org/templates-and-static-variables-in-c/
Upvotes: 2
Reputation: 172924
Note that the template instantiations with different type are irrelevant. It means if you called test()
three time with different type T
, then three irrelevant test()
will be instantiated, with 3 diffrent instances of vec
. That's why you're getting the result that their size are all 1
.
Upvotes: 4