处理构造函数时使用智能指针

Smart pointers when dealing with constructors

本文关键字:智能 指针 构造函数 处理      更新时间:2023-10-16

这个问题是关于我的程序的。我以前使用指针使用手动管理,现在我正尝试转向智能指针(出于所有好的理由)。

在普通指针中,使用new关键字很容易调用类的构造函数。如下面的程序:

Button * startButton;
startButton = new Button(int buttonID, std::string buttonName);

当使用智能指针时,调用类的构造函数的替代方法是什么?我在下面所做的会产生一个错误:

std::unique_ptr<Button> startButton;
startButton = std::unique_ptr<Button>(1, "StartButton"); // Error
我得到的错误如下:
Error   2   error C2661: 'std::unique_ptr<Button,std::default_delete<_Ty>>::unique_ptr' : no overloaded function takes 2 arguments

std::unique_ptr是一个指针的包装器,所以要创建一个正确的std::unique_ptr对象,你应该传递一个指针给它的构造函数:

startButton = std::unique_ptr<Button>(new Button(1, "StartButton"));

自c++ 14以来,还有一个辅助函数make_unique,它在底层为您完成此分配:

startButton = std::make_unique<Button>(1, "StartButton");

如果可以使用std::make_unique,因为它更容易阅读,在某些情况下使用它比直接使用new更安全。

如果你有支持c++ 14的编译器,你可以使用:

startButton = std::make_unique<Button>(1, "StartButton");

如果您被限制使用c++ 11,您需要使用:

startButton = std::unique_ptr<Button>(new Button(1, "StartButton"));