std::string 記憶體管理特別,多線程使用時應注意

來源:互聯網
上載者:User

轉自:http://blog.csdn.net/zhihuizhilv/article/details/5388946

VC2003開發程式,遇到一個崩潰的問題,經過苦苦查詢,發現和std::string的記憶體管理以及自己的使用方法有關。

std::string使用懶惰的記憶體管理原則。例如:

string str1 = "sdsada";

string str2 = str1;

這時兩個對象所指的字串記憶體其實是同一塊記憶體。也就是說,當通過str1構造str2的時候,str2並沒有立刻分配一塊自己的字串記憶體,而是直接使用str1的,另外將這塊記憶體的引用數加1。

不可思議的是,std::string並沒有考慮多線程的並發問題,導致在多個線程間操作共用字串記憶體的string對象時,可能出現問題。

 

為了避免這種隱患,只能保證多個線程操作的string對象間不要共用字串記憶體。該上面的代碼為:

string str2 = str1.c_str();

可以解決問題。

當然,也可以使用CString,就不用考慮這個問題啦。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.