Page 1 of 1

how to binding a class method with weak pointer?

PostPosted: Fri Jul 10, 2020 11:26 pm
by zhengtong0898
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?

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

PostPosted: Sat Jul 11, 2020 11:04 am
by magreenblatt
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.