jeudi 14 janvier 2021

C++: Memory leak with smart pointer when used with std::move

When a smart pointer is moved using std::move() how to clean the moved pointer? I have a layering like below and I am observing memory leak in the below code. How to explicitly free the moved pointer to the constructor of class Test?

#include <iostream>
#include <memory>

template <typename CharT>
class Test
{
public:
    Test() : _str(), _length() { }
    Test(const CharT* str, int length) : _str(str), _length(length) { }

private:
    int _length;
    const CharT* _str;
};

struct TestEntry
{
    TestEntry(const wchar_t* myarray, int length)
    {
        this->length = length;
        AllocateAndAssign(myarray, length);
    }

    TestEntry(const TestEntry& otherTestEntry)
    {
        this->length = otherTestEntry.length;
        AllocateAndAssign(std::move(otherTestEntry.myarray.get()), otherTestEntry.length);
        test = Test(std::move(this->myarray.get()), this->length);
    }

    ~TestEntry() 
    { 
        if(myarray)
          myarray.reset();
    }

    inline void AllocateAndAssign(const wchar_t* myarray, size_t length)
    {
        this->myarray = std::make_unique<wchar_t[]>(length + 1);
        wcscpy(this->myarray.get(), myarray);
    }

public:
    std::unique_ptr<wchar_t[]> myarray;
    int length;
    Test<wchar_t> test;
};

int main() {
    const wchar_t* src = L"MyTest";
    TestEntry e(src, 6);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire