使用我的共享指针获取内存泄漏

Getting memory leak with my shared pointers?

本文关键字:获取 内存 泄漏 指针 共享 我的      更新时间:2023-10-16

在我的基类中,我有一个派生类的指针向量,例如

std::vector<std::shared_ptr<Fing*>> files;

在我的派生抽象类中,我有一个工厂方法,看起来像

static std::shared_ptr<Fing*> create(const std::string filetype, const std::string &path);

派生抽象类 Fing* 还有另外三个派生类,我称之为派生的 A,B,C。所以我在shared_ptr基类中的向量实际上更像是shared_ptr<A* or B* or C*>的向量

所以工厂方法本身看起来像

shared_ptr<Fing*> Fing::create(const std::string fileType, const 
string &filepath){
if (fileType == "a"s){
    return make_shared<Fing*>(new A(filepath));
}
if (fileType == "b"s){
    return make_shared<Fing*>(new B(filepath));
}
    return make_shared<Fing*>(new C(filepath)); }

我这样称呼工厂方法

shared_ptr<Fing*> newA(Fing::create("a","path here"));

并像这样将其推送到我的矢量

myfiles.emplace_back(move(newA));

但是,即使我的基类被破坏了,valgrind 说我的工厂方法有泄漏?

问题是你不应该指定指向std::shared_ptr的参数是一个指针,这是隐式的。

所以你的声明需要更像这样:

class Fing
{
public:
    Fing(std::string const&) {}
    virtual ~Fing() {}
};
class A: public Fing { public: A(std::string const& s): Fing(s) {}};
class B: public Fing { public: B(std::string const& s): Fing(s) {}};
class C: public Fing { public: C(std::string const& s): Fing(s) {}};
std::vector<std::shared_ptr<Fing>> files;
std::shared_ptr<Fing> create(const std::string &filepath)
{
    return std::make_shared<A>(filepath);
}

std::shared_ptr是一个智能指针,它在内部为你保存一个指针,并管理它的生存期。 但是你滥用了std::shared_ptr. 切勿将其T模板参数设置为指针类型,而应设置为它应指向的实际类型。 指向指针会破坏使用智能指针的目的。

你也在滥用std::make_shared()。 使用 std::make_shared() 的全部意义在于避免必须显式使用new,并且比单独使用 new 更有效地分配初始std::shared_ptr<T>std::make_shared()分配您指定的T,并将其自己的参数转发给T 的构造函数。

自己动态分配

指针,然后创建一个具有自己的动态分配指针的std::shared_ptr,该指针是指针的副本,这是非常无用的。

试试这个:

std::vector<std::shared_ptr<Fing>> files;
...
std::shared_ptr<Fing> Fing::create(const std::string &fileType, const std::string &filepath)
{
    if (fileType == "a"s){
        return make_shared<A>(filepath);
    }
    if (fileType == "b"s){
        return make_shared<B>(filepath);
    }
    return make_shared<C>(filepath);
}
...
auto newA = Fing::create("a", "path here");
myfiles.push_back(std::move(newA));
or just:
myfiles.push_back(Fing::create("a","path here"));