STL线程安全

     由于需要,需要将一个int数组(vector)的内容写入到粘贴板中,最开始直接将vector作为ClipBoardData写入到站贴板,获取正确,但是存在内存泄漏,经实验,写入list等STL容器数据都会存在该情况,估计是由于STL的线程安全性一起的。

解决方法:

1、搞个结构体,放数组和大小,取的时候判断一下大小再按大小取数组内容。

2、将int数据先弄成string,然后在从粘贴板读取该数据后,再还原为int值。

 

     写入:

      COleDataSource objDataSrc;
    HGLOBAL hGlobal         = NULL;
    char*   pszBuffer       = NULL;
    FORMATETC  etc          = { CF_HDROP, NULL, DVASPECT_CONTENT, -1,    TYMED_HGLOBAL };
   
    //将index做成string(将vector直接写入粘贴板会导致内存泄漏。STL非线程安全)
    CString strIndex    = "";
    CString strTmp      = "";
   
    for(int nIndex = 0 ; nIndex < arr.size(); ++nIndex)
    {
        strTmp.Format("%d", arr[nIndex]);

        strIndex += strTmp;

        if (nIndex != arr.size() - 1)
        {
            strIndex += ",";
        }
    }
   
    hGlobal = GlobalAlloc(GHND, strIndex.GetLength() + 1);
   
    if ( NULL == hGlobal)
    {
        ASSERT(FALSE);
        return;
    }
   
    pszBuffer = (char*)GlobalLock(hGlobal);

    if ( NULL == pszBuffer )
    {
        ASSERT(FALSE);
        GlobalFree(hGlobal);
        return;
    }

    strcpy(pszBuffer, (LPCSTR)(strIndex));

    GlobalUnlock(hGlobal);
   
    objDataSrc.CacheGlobalData(uiFormat, hGlobal);
   
    objDataSrc.DoDragDrop();

 

 

读取:

       char* pszBuffer = (char*)GlobalLock(hGlobal);
        
        char* sep = ",";
        char* token;
        TIntArray arrSelIndex;

        token = strtok(pszBuffer, sep);       
       
        int nIndex = -1;
        while (NULL != token)
        {
            try
            {
                nIndex = boost::lexical_cast<int> (token);

                arrSelIndex.push_back(nIndex);
            }
            catch (...)
            {
                ASSERT(FALSE);
                return FALSE;
            }
            token = strtok(NULL, sep);
        }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值