how to binding a class method with weak pointer?

Having problems with building or using CEF's C/C++ APIs? This forum is here to help. Please do not post bug reports or feature requests here.

how to binding a class method with weak pointer?

Postby zhengtong0898 » Fri Jul 10, 2020 11:26 pm

i read document here https://chromium.googlesource.com/chromium/src.git/+/master/docs/callback.md#binding-a-class-method-with-weak-pointers that explain the weakptr.
i follow the guide and write the code below, it seems not work....

Code: Select all
class RefreshJsexecute {
public:
    RefreshJsexecute() {
        weak_this_ = weak_factory_.GetWeakPtr();     // break throw occur here in debug mode.....
    }                                                                                 
   
    void run(CefRefPtr<CefBrowser> browser) {
        if (browser.get()) browser->GetMainFrame()->ExecuteJavaScript("location.reload();", CefString(), 0);
    }

    void post_task(CefRefPtr<CefBrowser> browser) {
        CefPostDelayedTask(TID_UI, base::Bind(&RefreshJsexecute::run, weak_this_, browser), 10000);
    }

private:
    base::WeakPtr<RefreshJsexecute> weak_this_;
    base::WeakPtrFactory<RefreshJsexecute> weak_factory_{ this };
};


bool ResourceRequest::OnResourceResponse(CefRefPtr<CefBrowser> browser,
                                CefRefPtr<CefFrame> frame,
                                CefRefPtr<CefRequest> request,
                                CefRefPtr<CefResponse> response) {
    CEF_REQUIRE_IO_THREAD();
    if (request->GetURL() == "xxxxx") {
        RefreshJsexecute rj;
        rj.post_task(browser);
    }
    return false;
}


the break line is: weak_this_ = weak_factory_.GetWeakPtr();

can anyone solve this?
zhengtong0898
Newbie
 
Posts: 5
Joined: Fri Feb 21, 2020 10:34 am

Re: how to binding a class method with weak pointer?

Postby magreenblatt » Sat Jul 11, 2020 11:04 am

WeakPtr is not thread-safe, so the WeakPtrFactory initialization and GetWeakPtr need to be called on the same thread. You can pass a WeakPtr to and from a different thread, but it still can only be accessed (dereferenced) on the initialization thread.
magreenblatt
Site Admin
 
Posts: 12408
Joined: Fri May 29, 2009 6:57 pm


Return to Support Forum

Who is online

Users browsing this forum: No registered users and 54 guests