Error deleting std::vector in a DLL using the PIMPL idiom

前端 未结 2 427
独厮守ぢ
独厮守ぢ 2021-01-29 06:51

I have the following code:

In DLL1:

in .h file:

class MyClass
{
public:
    MyClass();
private:
    std::string m_name;
};

class __declspec(dlle         


        
2条回答
  •  再見小時候
    2021-01-29 07:16

    Without further code available for analysis, an important bug I see in your posted code is that your Foo class is a resource manager violating the so called Rule of Three.

    Basically, you dynamically allocate an Impl instance in the Foo constructor using new, you have a virtual destructor for Foo releasing the managed resource (pimpl) with delete, but your Foo class is vulnerable to copies.
    In fact, the compiler generated copy constructor and copy assignment operators perform member-wise copies, which are basically shallow-copies of the pimpl pointer data member: this is a source of "leaktrocities".

    You may want to declare private copy constructor and copy assignment for Foo, to disable compiler-generated member-wise copy operations:

    // Inside your Foo class definition (in the .h file):
    ...
    
    // Ban copy
    private:
        Foo(const Foo&); // = delete
        Foo& operator=(const Foo&); // = delete
    

    Note: The C++11's =delete syntax to disable copies is not available in MSVC 2010, so I embedded it in comments.


    Not directly related to your problem, but maybe worth noting:

    1. In your Foo::Impl structure, since the m_vec data member is already public, I see no immediate reason to provide an accessor member function like GetVector().

    2. Starting with C++11, consider using nullptr instead of NULL in your code.

提交回复
热议问题