一個由string使用不當產生的問題

來源:互聯網
上載者:User

今天因不正確的使用std::string,產生一個很難發覺的問題,搞了許久,mark一下。 原代碼大概如下:

void func(char *buf, int len){

string s;

s.reserve(len);

memcpy((char *)&s[0], buf, len));

string t(s, 0, len);

}

發現t中的資料始終為空白。 最後才明白,reserve函數沒有更改string的size,也就是說s.size()==0, 後面其它字串通過string的方法從s擷取資料,由於size為零,都不能真正拷貝資料。 解決方案很簡單,將reserve換成resize即可。可參考resize的源碼:

    610   template<typename _CharT, typename _Traits, typename _Alloc>
611 void
612 basic_string<_CharT, _Traits, _Alloc>::
613 resize(size_type __n, _CharT __c)
614 {
615 const size_type __size = this->size();
616 _M_check_length(__size, __n, "basic_string::resize");
617 if (__size < __n)
618 this->append(__n - __size, __c);
619 else if (__n < __size)
620 this->erase(__n);
621 // else nothing (in particular, avoid calling _M_mutate() unnecessarily.)
622 } // /usr/include/c++/4.1.0/bits/basic_string.tcc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.