c++ - 在构造函数中使用原始指针以立即将其包装在智能指针中是否被认为是不好的做法?
问题描述
我希望用户不必自己创建智能指针来传递给对象构造函数,而是传入原始指针,然后在初始化过程中转换为智能指针。但是,有一些关于创建内存泄漏的警钟响起,所以我想检查一下:以下代码是否有任何问题?
#include <memory>
using namespace std;
class A {
private:
std::unique_ptr<int> num;
public:
explicit A(int* n){
num = std::make_unique<int>(*n);
}
};
int main(){
int n = 4;
A a(&n);
// A a(std::make_unique<A>(n)); // instead of having to do this, which is a moderately irritating
};
解决方案
如果要避免接口中的智能指针,可以按值或常量引用使用:
class A {
private:
std::unique_ptr<int> num;
public:
explicit A(int n) : num(std::make_unique<int>(n)) {}
};
推荐阅读
- c - goto 语句导致无限循环
- jquery - jQuery范围滑块如何打破数千?
- javascript - 为什么 Object.keys() 中看不到 Object.defineProperties() 定义的属性?
- angular - Angular:发生未处理的异常:预期文件结尾,得到“,”defaultProject“......”
- vba - 浏览网站时如何点击按钮?
- python - 会员频道权限更新?
- wordpress - 链接预览未在任何社交媒体上显示
- python - 以json格式导出html数据
- fullpage.js - Fullpage JS - 滚动时导航点的大小不会改变
- rabbitmq - pika 中 add_callback_threadsafe() 方法有什么用?