Вы возвращаете ссылку на локальную переменную здесь.
Pair *pairFactory() {
Pair P;
P.check();
return &P; // Dangling pointer
}
Таким образом, у вас есть свисающий указатель, как только вы покидаете функцию.
Вы должны вызвать new
.
Pair *pairFactory()
{
return new Pair{};
}
main может выглядеть так:
int main() {
Pair* p = pairFactory();
// This function call should work without crashing:
p->check();
// Deallocating the heap memory. (Assuming it was made on the heap!)
delete p;
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}
Лучше использовать умный указатель, чтобы не приходилось управлять памятью самостоятельно:
std::unique_ptr<Pair> pairFactory()
{
return std::make_unique<Pair>();
}
int main() {
auto p = pairFactory();
p->check();
std::cout << "If you can see this text, the system hasn't crashed yet!" << std::endl;
}