|
CTempLock (&(this->m_Lock));
m_Lock a CCriticalSection.
There is a variable without name? what is it?
|
|
|
|
|
yu-jian wrote: There is a variable without name? What exactly are you referring to?
One of these days I'm going to think of a really clever signature.
|
|
|
|
|
That code creates (and destroys) a temporary CTempLock object. The net effect is the call of the class constructor and destructor. Try the following code:
#include <iostream>
using std::cout;
using std::endl;
class A
{
public:
A(){cout << "ctor" << endl;}
~A(){cout << "dtor" << endl;}
};
int main()
{
A();
}
Veni, vidi, vici.
|
|
|
|
|
It's the same with my code. But i am silly why the c plus plus allow defining a variable without name?
|
|
|
|
|
For instance, this allows you writing:
vector <A> v;
v.push_back(A());
Veni, vidi, vici.
|
|
|
|
|
Do you think that it's right? ~A() will be called after A() immediately.
|
|
|
|
|
yu-jian wrote: why the c plus plus allow defining a variable without name?
It isn't doing that.
You are confusing 'variable' with 'expession'.
In the following the left 'x' is a varible while the right side is an expression. The execution of the expression is not dependent upon the variable. The variable is just where the result of the expression is stored.
x = doSomething();
|
|
|
|
|
Your line with "CTempLock (&(this->m_Lock));" will create an unnamed variable of type CTempLock, call the destructor specified, and then call the destructor and destroy the object.
As another poster pointed out, using a constructor reference in this way, is supported as a means to pass temporary objects to a function.
The temporary object only exists on the stack, long enough to make a function call, that is intended to use the temporary object as a reference.
modified 16-Jan-13 17:28pm.
|
|
|
|
|
Right. Perhaps, it can use this way to do something in the constructor function of CTempLock.
|
|
|
|
|
Yes.
1. The object is created on the stack.
2. The constructor is called.
3. The destructor is called.
4. The object is then forgotten.
The example you provided is a good demo of how you can introduce locking bugs. Because the object goes out of scope right away, it doesn't really do anything useful.
The proper way to do it is:
CTempLock Lock(&(this->m_Lock));
If you do something like this...
void ProcessLock(const CTempLock & TempLock)
{
}
ProcessLock(CTempLock(&(this->m_Lock)));
Then the temporary object will exist for the lifetime of the call.
|
|
|
|