简体   繁体   English

C ++ - 如何调用用户定义的运算符?

[英]C++ — how to call user defined operator?

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? 这是一个问题:如何使用运算符WINDOW_HANDLE()来获取原始指针? I list my guess as follows: 我列出我的猜测如下:

WindowHandle win(createWindow());

WINDOW_HANDLE winPtr = win.operator WINDOW_HANDLE(); // I am not sure whether this is correct.

Thank you 谢谢

Simply 只是

WINDOW_HANDLE winPtr = win;

is sufficient. 足够了。 User-defined operators create implicit conversions. 用户定义的运算符创建隐式转换。

它允许你施放:

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. 因此,您进行一次创建WINDOW_HANDLE的调用,然后将其放入包装器类中,该类将为您关闭它。

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. 运营商WINDOW_HANDLE(合法,ThiefMaster,它是隐式转换)的目的是允许用户将WindowHandle传递给实际需要WINDOW_HANDLE的函数。 The conversion should be a const method. 转换应该是const方法。 (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. get()方法更可取。

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 没有必要编写这样的代码,因为你可以使用boost::unique_ptr用于此目的,如果你不需要它可以复制和boost :: shared_ptr,如果你这样做,并且在任何一种情况下你用删除函数创建它,在这种情况下DestroyWindow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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