简体   繁体   中英

does operator () parenthesis get called on object created within a function call?

I have a class that acts like a "smart pointer" for handles.

#define DEST 123

HANDLE OpenHandle(int dest);
class SmartHandle;
void SendMsg(HANDLE dest_handle);

SendMsg(SmartHandle(OpenHandle(DEST)))

This construct is used often in my code so it does work but I don't understand why.

OpenHandle(DEST) returns a handle to the "smart pointer" class

SendMsg - takes an argument of the same type that is return by OpenHandle which is a simple HANDLE aka void*

For this thing to work, and it does, it must mean that HANDLE SmartHandle::operator() is invoked.

QUESTION

Why does HANDLE SmartHandle::operator() get invoked?

Looking at the code, I would just say that an object of type SmartHandle is created and nothing is returned and then SmartHandle destructor is called.

No, a call such as:

HANDLE h;
SmartHandle(h);

Does not call SmartHandle::operator() . Instead, it creates a temporary object of type SmartHandle , constructed with the h argument. That is, it is calling the constructor SmartHandle::SmartHandle(HANDLE) .

Your code works because you class most likely has a operator HANDLE() to convert an object of your type back into a HANDLE . So you code does this sequence of operations:

{
  HANDLE tmp1 = OpenHandle(DEST);
  SmartHandle tmp2(tmp1);
  HANDLE tmp3 = tmp2.operator HANDLE();
  SendMsg(tmp3);
}     //at the end of the full sentence temporaries are destroyed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM