C++学习笔记 44 C++17 std::string_view 字符串优化

一、std::string_view

它本质上只是一个指向现有内存的指针,换句话说,就是一个const char* , 指向其他人拥有的现有字符串,再加上一个大小size

冷知识:const char定义字符串变量比std::string定义字符串变量省内存。
const char
本质就是指针变量,这个指针变量在32位系统中只占4个字节,在64位系统中只占8个字节。
而string是占了整整40个字节

一、现有字符串使用中的多次malloc内存分配

#include<iostream>
#include<string>

static uint32_t s_AllocCount = 0;

//重写new关键字,统计string对象时分配了多少次内存
void* operator new(size_t size) {
	s_AllocCount++;
	std::cout << "Allocationg " << size << " bytes." << std::endl;
	return malloc(size);
}

void PrintName(const std::string& name) {
	std::cout << name << std::endl;
}

void PrintName(std::string_view name) {
	std::cout << name << std::endl;
}


int main() {
	//release 模式 和 debug模式,allocate的次数不一样
	//1. 这一行会在堆中分配内存 std::basic_string
	std::string name = "12345678";		//allocate 1次
	//const char* name = "12345678";
	//PrintName(name);
	//2. 直接传递字符串也会触发分配内存
	//PrintName("Hello World sdadfasdf");
#if 0
	//创建了新的字符串
	std::string firstName = name.substr(0, 3);	//allocate 1次
	std::string secondName = name.substr(4, 9);	//allocate 1次
#elif 1
	//std::string name 没有新创建字符串
	std::string_view firstName(name.c_str(), 3);
	std::string_view secondName(name.c_str() + 4, 9);

	//const char* name, 这将会将allocate的次数缩减为0
	//std::string_view firstName(name, 3);
	//std::string_view secondName(name + 4, 9);
#endif

	PrintName(firstName);
	std::cout << s_AllocCount << " allocations" << std::endl;
	std::cin.get();
}

posted @ 2025-12-31 18:07  超轶绝尘  阅读(3)  评论(0)    收藏  举报