1. std::string 的預(yù)留空間

#include <iostream>
#include <string>
#include <string.h>

using std::cout;
using std::endl;

/**
 * Note: 增加了奇怪的知識(shí)點(diǎn):
 * 1. std::string 創(chuàng)建的每個(gè)對(duì)象,都會(huì)預(yù)留15個(gè)字節(jié)的空間;
 * 2. std::string(""), 預(yù)留了15個(gè)字節(jié)的空間;
 * (就像創(chuàng)建了一個(gè)空的倉(cāng)庫(kù),倉(cāng)庫(kù)里面沒(méi)放東西。但是, 如果其他人有倉(cāng)庫(kù)鑰匙的話,依然可以使用這個(gè)倉(cāng)庫(kù))
 * 
 * str.capacity(): 返回當(dāng)前為字符串分配的存儲(chǔ)空間大小,以字節(jié)表示。
 *
 * data(): const char* data() const noexcept;
 * c_str(): const char* c_str() const noexcept;
 * Both string::data and string::c_str are synonyms and return the same value.
 * 官方解釋?zhuān)篸ata() 和 c_str() 是一樣的
 * 
 *
*/

int main() {

    // init empty string
    std::string str("");
    std::cout << "size: "       << str.size()       << endl;
    std::cout << "length: "     << str.length()     << endl;
    std::cout << "capacity: "   << str.capacity()   << endl;
    std::cout << "max_size: "   << str.max_size()   << endl;
    std::cout << "data: "       << str.data()       << endl;
    std::cout << "Address of str: " << &str << endl;

    char *mch = (char*)str.data();
    std::cout << "mch: " << mch << endl;
    std::cout << "Address of mch: " << static_cast<void *>(mch) << endl;

    char tem[5] = "q3we"; // '\0'

    memcpy((void*)(str.c_str()), tem, 5);
    std::cout << "size: "       << str.size()       << endl;
    std::cout << "length: "     << str.length()     << endl;
    std::cout << "capacity: "   << str.capacity()   << endl;
    std::cout << "max_size: "   << str.max_size()   << endl;
    std::cout << "data: "       << str.data()       << endl;
    std::cout << "Address of str: " << &str << endl;

    return 0;
}

結(jié)果:
size: 0
length: 0
capacity: 15
max_size: 9223372036854775807
data: 
Address of str: 0x7ffc76fa61f0
mch: 
Address of mch: 0x7ffc76fa6200
size: 0
length: 0
capacity: 15
max_size: 9223372036854775807
data: q3we
Address of str: 0x7ffc76fa61f0
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容