#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.
* 官方解釋:data() 和 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