简体   繁体   English

在构造函数中使用原始指针以立即将其包装在智能指针中是否被认为是不好的做法?

[英]Is it considered bad practice to use a raw pointer in a constructor with the intention of wrapping it immediately in a smart pointer?

I want users not to have to create smart pointers to pass into object contructors themselves, but instead to pass in a raw pointer and then convert to a smart pointer within the initialisation.我希望用户不必自己创建智能指针来传递给 object 构造函数,而是传入原始指针,然后在初始化中转换为智能指针。 However, there are some warning bells ringing regarding creating memory leaks so I wanted to check: Is the following code problematic in any way?但是,有一些关于创建 memory 泄漏的警钟响起,所以我想检查一下:以下代码有任何问题吗?


#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 

};

If you want to avoid smart pointer in interface, you might use by value or const reference:如果要避免接口中的智能指针,可以按值或常量引用使用:

class A {
private:
    std::unique_ptr<int> num;

public:
    explicit A(int n) : num(std::make_unique<int>(n)) {}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM