使用我的共享指针获取内存泄漏
Getting memory leak with my shared pointers?
在我的基类中,我有一个派生类的指针向量,例如
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"));
- 从'deleted function'获取内存错误
- 如何让 'std::vector' <int32_t>从 'std::vector&&' 中获取内存<uint32_t>?
- Qt QProcess 获取内存信息
- 如何从eigen :: matrix获取内存所有权
- 使用我的共享指针获取内存泄漏
- 混合放松和释放获取内存顺序
- 从动态分配的阵列获取内存泄漏
- 使用 PID 获取内存和 CPU 使用率
- 使用标准化函数/OPENCV和C 获取内存分配错误
- 获取内存值数组的最快方法
- 获取内存地址 X 处的值
- 在 C# 中获取内存中的下一个对象大小的空间
- 获取内存中 PE 标头的虚拟地址
- 获取内存地址处的值
- 用c++获取内存缓冲区
- 如何获取内存中字符串实际占用的字节数
- 以下数组从何处获取内存
- 用acq_rel顺序获取内存
- 在c++中获取内存之后的strlen
- 如何从字符串中获取内存地址