处理构造函数时使用智能指针
Smart pointers when dealing with constructors
这个问题是关于我的程序的。我以前使用指针使用手动管理,现在我正尝试转向智能指针(出于所有好的理由)。
在普通指针中,使用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"));
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 优先顺序:智能指针和类析构函数
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 智能指针作为无序映射键,并通过引用进行比较
- 智能指针概念所有权和寿命
- 正在理解智能指针,但出现错误:未分配正在释放的指针
- 尝试使用智能指针时引发异常
- 我可以制作指向智能指针的智能指针吗?
- 通过智能指针和转换对基本模板参数进行模板推导
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 从堆栈分配的原始指针构造智能指针
- 初始化指向类实例的智能指针并访问其方法
- 如何使用 std::make_shared 创建基类类型的智能指针?
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 编译器不会使用 -std=c++11 编译智能指针
- 具有智能指针的多态性
- C++:矢量分配器行为、内存分配和智能指针
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 指向函数签名中的常量智能指针
- 使用智能指针附加的继承对象的深层复制