I have made a minial example for my question:
#include <bits/stdc++.h>
using namespace std;
class Data
{
};
class Base
{
private:
Data data1_;
int x{1};
public:
explicit Base(Data data) : data1_(data)
{
cout << "Base constructor" << endl;
}
Base(Base &&b) : data1_(std::move(b.data1_)), x(std::move(b.x))
{
cout << "Base move constructor" << endl;
}
virtual ~Base()
{
cout << "Base destructor" << endl;
}
};
class Derived : public Base
{
private:
Data data2_;
public:
explicit Derived(Data data1, Data data2) : Base(data1), data2_(data2)
{
cout << "Derived constructor" << endl;
};
Derived(Base &&b, Data data2) : Base(std::move(b)), data2_(data2)
{
cout << "Derived move constructor" << endl;
}
~Derived()
{
cout << "Derived destructor" << endl;
}
};
void foo()
{
unique_ptr<Base> owner = make_unique<Base>(Data());
unique_ptr<Base> *ptr1 = &owner;
Base *base = ptr1->release();
ptr1->reset(new Derived(std::move(*base), Data()));
cout << sizeof(Base) << endl;
}
int main()
{
foo();
return 0;
}
In the above example, sometimes, there will be 16 bytes memory leak in my code.(detected by clang LeakSanitizer):
foo()
function is what i need to do, i.e. replace Base with Derived depending on the pointer to unique_ptr and the move constructor of Derived.
Under this scenario, what's my best solution to avoid memory leak and make full use of the move constructors? What's more, what's the best practice to deal with non-class members in move constructor?