Given a simple class in C++ with a private member variable name and a basic constructor:
#include <QString>
class Testclass
{
private:
QString *name;
public:
Testclass(): name(new QString()) {}
};
Why does valgrind’s memcheck complains about 8 bytes in 1 block, which are definitely lost when using this constructor?
Will plug your leak. C++ doesn’t (and shouldn’t) do this for you.
ETA: ildjarn correctly points out that you should also have a copy constructor and assignment operator.
Otherwise, the default copy constructor or assignment operator will cause the same memory to be deleted twice. Most classes that require a destructor should replace or disable the default copy constructor and assignment operator. This is called the “Rule of Three.”
You might want to consider simply holding the QString by value, because it’s likely itself a lightweight container class, like std::string or std::vector. But if you’re a C++ beginner, doing it this way once is a valuable lesson.