C++幾個技巧:智能指針在消息傳遞中的使用,元組,及lambda刪除器

1.SendMessage/PostMessage中傳遞對象參數python

(1)方法1:使用shared_ptrc++

發送端:windows

PostMessage(MyhWnd, CWM_SOME_ERROR, 0, reinterpret_cast<LPARAM>(new string(the_exception.error_string)) );promise

接收端:數據結構

LPARAM CMyDlg::OnMyMessage1(WPARAM, LPARAM lParam)
{
    // Put in shared_ptr so it is automatically destroyed.
    shared_ptr<string> msg = reinterpret_cast<string*>(lParam);

    // Do stuff with message

    return 0;
}

(2)方法2:使用unique_ptr,更嚴謹併發

SendingMethod::SendMsgId( ... )
{
    ...

    std::unique_ptr<MyParams> myParams( new MyParams(value1, value2, value3) );
    if (PostThreadMessage(MSG_ID, 0, reinterpret_cast<LPARAM>(myParams.release())) {
        myParams.release();    // is postmessage failed
} ... } ReceivingMethod::OnMsgId( WPARAM wParam, LPARAM lParam) { std::unique_ptr
<MyParams> myParams( reinterpret_cast<MyParams*>(lParam) ); ... // use object }

(3)方法3:enable_shared_from_thissocket

 LPARAM所指向的對象從enable_shared_from_this派生,例如:post

class A : public enable_shared_from_this<A> {測試

}this

發送端:

shared_ptr<A> p = shared_from_this();

發送對象p

接收端: shared_from_this();獲取對象

理論可行,但這種侵入式的設計影響LPARAM類,不想作嘗試

 

(4)方法4:std::promise, std::future and std::get_future

更高端的併發方式,後面有空補充

 

注:不要再使用auto_ptr,新的c++標準不推薦

 

 

2.刪除器和lambda

char *buffer = (char *)malloc(len);

std::shared_ptr<void> _free_ptr((void *)buffer, [](void *p){
free(p);
});

一樣,也適合close socket/file等,參考<<C++primer>>中文第五版416頁

 

3.元組

雖然c++不是python類型的動態語言(類型和值都是變量的動態特性),tuple的出現有了很大的彌補,vs2013update5可用因此順便測試了一下:

    // 建立及獲取元組內的對象
    std::tuple<double, std::string> tup1(3.14, "pi");
    auto tup2 = std::make_tuple("Hello World!", "abc", 3.14, 0);
    const char* data = std::get<1>(tup2);    // 獲得abc
    double len = std::get<2>(tup2);        // 獲得3.14

    // 拆箱:tie參數做爲左值
    auto tup3 = std::make_tuple(3.14, 1, 'a');
    double a;
    int b;
    std::tie(a, b, std::ignore) = tup3;

windows種傳遞消息(PostMessage(wparam,lparam)), 若是lparam是某個數據結構,那麼能夠用unique_ptr對象傳遞一個元組,很是省事

相關文章
相關標籤/搜索