开发者

C++ -- how to call user defined operator?

开发者 https://www.devze.com 2023-02-13 21:29 出处:网络
I saw the following code snippet: class WindowHandle { public: WindowHandle(WINDOW_HANDLE handle) : w(handle) {}

I saw the following code snippet:

class WindowHandle {
public:
  WindowHandle(WINDOW_HANDLE handle) : w(handle) {}
  ~WindowHandle() { destoryWindow(w); }

  operator WINDOW_HANDLE() { return w; }
  ...

private:
  WINDOW_HANDLE w;
  ...
}

Here is the question: how do I use operator WINDOW_HANDLE() to get the raw pointer? I list my guess as follows:

WindowHandle win(createWindow());

WINDOW_HANDLE winPtr = win.operator W开发者_开发技巧INDOW_HANDLE(); // I am not sure whether this is correct.

Thank you


Simply

WINDOW_HANDLE winPtr = win;

is sufficient. User-defined operators create implicit conversions.


It allows you to cast:

WINDOW_HANDLE winPtr = static_cast<WINDOW_HANDLE>(win);


The purpose of the code you are showing is to automatically close a handle. Thus you make a call that creates a WINDOW_HANDLE and you put it into the wrapper class which will close it for you.

The main issue is that it has an implicit constructor, no overloaded copy-constructor or assignment operator, and its destructor destroys the handle.

Thus you could well get into trouble with that implementation.

The purpose of the operator WINDOW_HANDLE (which is legal, ThiefMaster, it's an implicit conversion), is to allow the user to pass a WindowHandle into a function that actually requires a WINDOW_HANDLE. The conversion should be a const method. (It is not passing a reference, after all).

Although the language has given you such a feature it is preferable not to use it. A get() method is preferable.

There is no need to write code like this as you can use boost::unique_ptr for this purpose if you do not need it to be copyable and boost::shared_ptr if you do, and in either case you create it with a deleter function, in this case DestroyWindow

0

精彩评论

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