You should add a copy constructor:
struct Parameter { QString stringPar; Parameter& Parameter(const Parameter& rhs) { if((void*)this == (void*)&rhs) { return *this; } this->stringPar = rhs.stringPar; return *this; } };
A Temp Parameter instance is created when you call ClassA :: function () due to passing C ++ arguments by value; Something like that:
void ClassA::function(Parameter pars = QString("jkjsdghdkjhgdjufgskhdbfgskzh")) { m_string1 = pars.stringPar;
If you did not write a copy constructor, the compiler will synthesize the default copy constructor, for example:
Parameter& Parameter(const Parameter& rhs) { memcpy(this, &rhs, sizeof(Parameter)); return *this; }
I assume that QString has pointer elements, considering it with the name ptr. then pars.stringPar.ptr and QString ("jkjsdghdkjhgdjufgskhdbfgskzh"). stringPar.ptr will point to the same memory address.
Call the function as follows:
classA.function({ QString("jkjsdghdkjhgdjufgskhdbfgskzh") });
{QString ("jkjsdghdkjhgdjufgskhdbfgskzh")} destroy the object before calling classA.function (), then the memory pointed to by {QString ("jkjsdghdkjhgdjufgskhdbfgskzh")}. stringPar.ptr is freed, and pars.stringPar.ptr points to invalid memory.
// when using this code the problem does not occur //Parameter par1 = { QString("jkjsdghdkjhgdjufgskhdbfgskzh") }; //classA.function(par1) //par1 destroy when main() function return, thus classA.function() does not crash.
See <Efficient C ++ → Clause 11: declare a copy constructor and assignment operator for classes with dynamically allocated memory. Effective C ++, 2E http://debian.fmi.uni-sofia.bg/~mrpaff/Effective%20C++/EC/EI11_FR.HTM