簡體   English   中英

重載unique_ptr運算符調用make_unique

[英]overload unique_ptr operator call make_unique

我想在std :: unique_ptr中添加一個運算符,這樣我就可以添加make_unique而無需在代碼中添加make_unique

我希望能夠做到這一點

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));

這是不可能的。 operator=必須是成員函數,並且您不能將自己的內容添加到unique_ptr類。

即使有可能,這也不是一個好主意,因為:

  • 這將破壞operator=的有效用例對unique_ptr
  • 人們閱讀代碼不會期望這種意外的行為

可以從派生類中的unique_ptr和重載operator=派生,但是再次使任何閱讀代碼的人感到困惑(如果您在一段時間后重新訪問該項目,則可能包括您自己)。

正如評論中所建議的那樣,最好僅創建一些命名函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM