简体   繁体   English

重载unique_ptr运算符调用make_unique

[英]overload unique_ptr operator call make_unique

I would like to add a operator to std::unique_ptr so i can add make_unique without adding make_unique to code 我想在std :: unique_ptr中添加一个运算符,这样我就可以添加make_unique而无需在代码中添加make_unique

i would like to be able to do it something like this 我希望能够做到这一点

namespace Window
{
    class CWindow;

    typedef std::unique_ptr<CWindow> Window;

    template<typename... Args>
    Window::operator=(Args&&... args)
    {
        return std::make_unique<CWindow>(std::forward<Args>(args)...);
    }
}

//global
Window::Window MainWindow;

//In WinMain
MainWindow = Window::CWindow("Window Name", Vector2D(10, 10), Vector2D(500, 500));

This is not possible. 这是不可能的。 operator= must be a member function, and you cannot add your own stuff to the unique_ptr class. operator=必须是成员函数,并且您不能将自己的内容添加到unique_ptr类。

Even if it were possible, it would be a bad idea because: 即使有可能,这也不是一个好主意,因为:

  • it would break the behaviour of valid use cases of operator= for unique_ptr 这将破坏operator=的有效用例对unique_ptr
  • people reading the code will not expect this unexpected behaviour 人们阅读代码不会期望这种意外的行为

You could derive from unique_ptr and overload operator= in the derived class, but again it will confuse anyone reading the code (including yourself probably, if you revisited the project after a period of time). 可以从派生类中的unique_ptr和重载operator=派生,但是再次使任何阅读代码的人感到困惑(如果您在一段时间后重新访问该项目,则可能包括您自己)。

As suggested in comments, it would be better just to make some named function. 正如评论中所建议的那样,最好仅创建一些命名函数。

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

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