#include <iostream>
#include <string>
#include <string.h>
using std::cout;
using std::endl;
/**
* Note: 增加了奇怪的知识点:
* 1. std::string 创建的每个对象,都会预留15个字节的空间;
* 2. std::string(""), 预留了15个字节的空间;
* (就像创建了一个空的仓库,仓库里面没放东西。但是, 如果其他人有仓库钥匙的话,依然可以使用这个仓库)
*
* str.capacity(): 返回当前为字符串分配的存储空间大小,以字节表示。
*
* 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;
}
结果:
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