将 SharedPtr 与 std::list 一起使用时内存泄漏!错误

Memory Leak when using SharedPtr with std::list! Bug?

本文关键字:内存 泄漏 错误 一起 SharedPtr std list      更新时间:2023-10-16

VLD 在以下代码中检测到内存泄漏:

typedef Poco::SharedPtr<double> DoublePtr;
class A {
    public:
        DoublePtr a;
};
class B:public A {
    public:
        DoublePtr b;
};    
class C : public B
{
    public:
        DoublePtr c;
};
typedef Poco::SharedPtr<A> APtr;
typedef Poco::SharedPtr<B> BPtr;
typedef Poco::SharedPtr<C> CPtr;
class Test {
    public:
        Test() {
            CPtr c1 = new C();
            a_list.push_back(c1);
        }
        std::list<APtr> a_list;
};
int main(int argc, char *argv[])
{
    Test test;
}

但是使用 std::shared_ptr 或 boost::shared_ptr 代替时是可以的。 而且,如果我添加'virtual ~A(({}',Poco::SharedPtr 也可以!

是 Poco::Sharedptr 的错误吗?

A需要有一个虚拟析构函数;如果没有,则通过A指针删除BC对象会导致未定义的行为。未定义的行为可能包括内存泄漏。