Project

General

Profile

Dbo::ptr in event handler

Added by Tibor Miseta over 1 year ago

Could someone enlighten me what is wrong with this code?

class
Location : public Wt::Dbo::Dbo<Location> {
public:
    std::string name;

    template<class Action>
    void persist(Action& a)
    {
        Wt::Dbo::field(a, name, "name");
    }

    Location() {};
};

class LocationWidget : public Wt::WTreeView
{
public:
    LocationWidget( Wt::Dbo::ptr<Location> &location,
                    std::shared_ptr<Wt::WStandardItemModel> &model);

    void showPopup(const Wt::WModelIndex& item, const Wt::WMouseEvent& event);

private:
    Wt::Dbo::ptr<Location>                  location_;
    std::shared_ptr<Wt::WStandardItemModel> model_;
};

LocationWidget::
LocationWidget( Wt::Dbo::ptr<Location> &location,
                std::shared_ptr<Wt::WStandardItemModel> &model)
    : Wt::WTreeView(),
      location_(location),
      model_(model)
{
    setModel(model_);

    setAttributeValue // disables browser's context menu
        ("oncontextmenu",
         "event.cancelBubble = true; event.returnValue = false; return false;");

    mouseWentUp().connect(this, &LocationWidget::showPopup);

    std::cout << location_->name << " in LocationWidget() works" << std::endl;
};

void
LocationWidget::
showPopup(const Wt::WModelIndex& item, const Wt::WMouseEvent& event)
{
    if (event.button() == Wt::MouseButton::Right)
    {
        std::cout << location_->name << " in showPopup() does not work" << std::endl;
        // Results "Wt: error during event handling: using orphaned dbo ptr"
    }
}

I suspect the problem is that the event handler runs in a different thread to the constructor (at least on my computer), and thus the Dbo::ptr is orphaned because its thread unsafety. But what is the recommended pattern then if I must invoke a database operation in the event handler? (e.g. the content of the popup menu depends on the data.)

(This is just a stripped down skeleton to show the root cause. I attach the minimum code that compiles too. It shows five Items, and right-clicking on any of them invokes the event handler that fails.)

Thank you in advance for the advices!


Replies (1)

RE: Dbo::ptr in event handler - Added by Tibor Miseta over 1 year ago

Opps! I found my mistake! The session variable was a stack variable instead of a class member, so died before it should be.
Sorry for the noise!

    (1-1/1)