问题
In C++, when you have local variables in a static member function, does it mean those local variables are also implicitly static or are they really local?
example:
static void myClass::somefunc(int someint)
{
int myint = someint; // is myint really a local variable or does it change due to the static qualifier at function level?
}
Also, different threads from a thread pool running this function, does myint need to be protected by a lock? assuming that all values passed to it are different and have no relation to each other.
EDIT: Thanx for the answers. Now what if I passed in a boost::shared_ptr<T>
, knowing that this object would not be concurrently being used by another thread? (Not sure if one can really guarantee that, or can you?)
I guess a raw ptr passed in, would need some protection, if it were being used all over?
回答1:
They are local unless you declare them static
- each invokation of the function will have its own copy of the variable and you don't need to to protect them.
回答2:
myint
is local for somefunc
and you don't need to protect it across threads.
回答3:
myint in your example is a local variable, every time somefunc is called myint lives. but not more than that.
myint doesn't need to be protected because its a local variable
回答4:
myint
will truly be local. You don't have to worry about protecting it. A separate space will be created on the stack for myint
for every single function call in memory.
回答5:
The myint
variable will stay local, there is no need to protect them since each thread will not share the local variables.
回答6:
The static key-word means that the function will not be passed a hidden "this" argument. Also the function will not have access to the class instance data. The static qualifier of function, has no impact on function's local data.
The static RetType SomeClass::SomeMethod(Type arg)
has the same "type" as a free functionRetType SomeFunc(Type arg)
Regards,
Marcin
来源:https://stackoverflow.com/questions/4509850/static-member-function-and-thread-safety