Does postEvent receive an event after posting? (double freedom or corruption)

I am sending a custom event inherited from QEventusing QCoreApplication::postEvent. I read that when using postEventit is necessary to have a heap highlighted event. But I'm not sure who is responsible for this.

So, I tried to use std::shared_ptr. However, when I create my event using std::shared_ptr, I got this error:

double free or corruption (fasttop)

Does this mean that the QEventevent can be freed so that I can just create the event and not bother deleting it?

This is what the code looks like:

class MyCustomEvent : public QEvent {...}

std::shared_ptr<MyCustomEvent> evt(new MyCustomEvent(arg1, arg2)); // double free or corruption!
QCoreApplication::postEvent(targetObj, evt.get());
+4
source share
1 answer

From the documentation for QCoreApplication::postEvent:

, . .

, std::shared_ptr , .

, std::unique_ptr ( std::make_unique), release , . , , , , . , , , - Good Thing ™.

// C++14 idiomatic exception-safe event posting in Qt
auto evt = std::make_unique<MyCustomEvent>(arg1, arg2);
// intervening code that could throw
QCoreApplication::postEvent(targetObj, evt.release());

// C++11 idiomatic exception-safe event posting in Qt
std::unique_ptr<MyCustomEvent> evt { new MyCustomEvent(arg1, arg2) };
// intervening code that could throw
QCoreApplication::postEvent(targetObj, evt.release());

// C++98 idiomatic exception-safe event posting in Qt
QScopedPointer<MyCustomEvent> evt (new MyCustomEvent(arg1, arg2));
// intervening code that could throw
QCoreApplication::postEvent(targetObj, evt.take());
+5

Source: https://habr.com/ru/post/1607428/


All Articles