C++ 重载唯一\u ptr操作员调用使唯一
我想在std::unique\u ptr中添加一个操作符,这样我就可以添加make\u unique,而无需将make\u unique添加到代码中 我希望能做到这样C++ 重载唯一\u ptr操作员调用使唯一,c++,C++,我想在std::unique\u ptr中添加一个操作符,这样我就可以添加make\u unique,而无需将make\u unique添加到代码中 我希望能做到这样 namespace Window { class CWindow; typedef std::unique_ptr<CWindow> Window; template<typename... Args> Window::operator=(Args&&..
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));
名称空间窗口
{
CWindow类;
typedef std::唯一的\u ptr窗口;
模板
窗口::运算符=(Args&&…Args)
{
返回std::make_unique(std::forward(args)…);
}
}
//全球的
窗口::窗口主窗口;
//在温曼
MainWindow=Window::CWindow(“窗口名称”,Vector2D(10,10),Vector2D(500500));
这是不可能的operator=
必须是成员函数,并且不能将自己的内容添加到unique\u ptr
类中
即使有可能,这也不是一个好主意,因为:
- 它将破坏
的操作符=
unique\u ptr
- 阅读代码的人不会预料到这种意外行为
unique\u ptr
派生并重载operator=
,但这同样会使任何阅读代码的人感到困惑(如果您在一段时间后再次访问该项目,可能包括您自己)
正如在注释中所建议的,最好只创建一些命名函数 这是不可能的
operator=
必须是成员函数,并且不能将自己的内容添加到unique\u ptr
类中
即使有可能,这也不是一个好主意,因为:
- 它将破坏
的操作符=
unique\u ptr
- 阅读代码的人不会预料到这种意外行为
unique\u ptr
派生并重载operator=
,但这同样会使任何阅读代码的人感到困惑(如果您在一段时间后再次访问该项目,可能包括您自己)
正如在注释中所建议的,最好只创建一些命名函数 为什么不
template Window CreateWindow(Ts&&…args){return make_unique(std::forward(args)…)}
?因为我以这种方式添加其他窗口控件,这些控件具有指向主窗口/选项卡的指针operator=
只接受一个参数。为什么不简单地将使用make_unique
制作的unique_ptr
分配给MainWindow
?@GeorgeSovetov你的意思是什么?MainWindow=std::make_unique(“Window Name”,Vector2D(10,10),Vector2D(500500))
。为什么不模板Window CreateWindow(Ts&…args){返回make_unique(std::forward(args);})
?因为我以这种方式添加其他窗口控件,这些控件具有指向主窗口/选项卡的指针操作符=
只接受一个参数。你为什么不简单地将使用make_unique
制作的unique\ptr分配给MainWindow
?@GeorgeSovetov你的意思是什么?MainWindow=std::make_unique(“窗口名”),Vector2D(10,10),Vector2D(500))
unique\u ptr
是一个模板,您可以添加自己的部分专业化,尽管在这种情况下标准威胁您使用UB。unique\u ptr
是一个模板,您可以添加自己的部分专业化,尽管在这种情况下标准威胁您使用UB。